szurubooru/public_html/js/Promise.js

87 lines
2.4 KiB
JavaScript
Raw Normal View History

2014-09-04 18:06:25 +02:00
var App = App || {};
App.Promise = function(_, jQuery, progress) {
2014-09-04 18:06:25 +02:00
2015-06-28 10:07:11 +02:00
function BrokenPromiseError(promiseId) {
this.name = 'BrokenPromiseError';
this.message = 'Broken promise (promise ID: ' + promiseId + ')';
}
BrokenPromiseError.prototype = new Error();
2015-06-28 10:07:11 +02:00
var active = [];
var promiseId = 0;
2014-10-02 00:30:25 +02:00
2015-06-28 10:07:11 +02:00
function make(callback, useProgress) {
var deferred = jQuery.Deferred();
var promise = deferred.promise();
promise.promiseId = ++ promiseId;
2014-10-02 00:30:25 +02:00
2015-06-28 10:07:11 +02:00
if (useProgress === true) {
progress.start();
}
callback(function() {
try {
deferred.resolve.apply(deferred, arguments);
active = _.without(active, promise.promiseId);
progress.done();
} catch (e) {
if (!(e instanceof BrokenPromiseError)) {
console.log(e);
}
progress.reset();
}
}, function() {
try {
deferred.reject.apply(deferred, arguments);
active = _.without(active, promise.promiseId);
progress.done();
} catch (e) {
if (!(e instanceof BrokenPromiseError)) {
console.log(e);
}
progress.reset();
}
});
2014-10-02 00:30:25 +02:00
2015-06-28 10:07:11 +02:00
active.push(promise.promiseId);
2014-10-04 22:46:28 +02:00
2015-06-28 10:07:11 +02:00
promise.always(function() {
if (!_.contains(active, promise.promiseId)) {
throw new BrokenPromiseError(promise.promiseId);
}
});
2014-10-02 00:30:25 +02:00
2015-06-28 10:07:11 +02:00
return promise;
}
2014-10-02 00:30:25 +02:00
2015-06-28 10:07:11 +02:00
function wait() {
var promises = arguments;
var deferred = jQuery.Deferred();
return jQuery.when.apply(jQuery, promises)
.then(function() {
return deferred.resolve.apply(deferred, arguments);
}).fail(function() {
return deferred.reject.apply(deferred, arguments);
});
}
2014-09-04 18:06:25 +02:00
2015-06-28 10:07:11 +02:00
function abortAll() {
active = [];
}
2014-09-04 18:06:25 +02:00
2015-06-28 10:07:11 +02:00
function getActive() {
return active.length;
}
2014-09-04 18:06:25 +02:00
2015-06-28 10:07:11 +02:00
return {
make: function(callback) { return make(callback, true); },
makeSilent: function(callback) { return make(callback, false); },
wait: wait,
getActive: getActive,
abortAll: abortAll,
};
2014-09-04 18:06:25 +02:00
2014-09-08 22:02:28 +02:00
};
2014-09-04 18:06:25 +02:00
App.DI.registerSingleton('promise', ['_', 'jQuery', 'progress'], App.Promise);