szurubooru/public_html/js/Promise.js

84 lines
1.7 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
function BrokenPromiseError(promiseId) {
this.name = 'BrokenPromiseError';
this.message = 'Broken promise (promise ID: ' + promiseId + ')';
}
BrokenPromiseError.prototype = new Error();
2014-10-02 00:30:25 +02:00
var active = [];
2014-10-04 13:15:18 +02:00
var promiseId = 0;
2014-10-02 00:30:25 +02:00
function make(callback) {
var deferred = jQuery.Deferred();
var promise = deferred.promise();
2014-10-04 13:15:18 +02:00
promise.promiseId = ++ promiseId;
2014-10-02 00:30:25 +02:00
progress.start();
2014-10-02 00:30:25 +02:00
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();
}
2014-10-02 00:30:25 +02:00
}, 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
});
2014-10-04 22:46:28 +02:00
active.push(promise.promiseId);
promise.always(function() {
2014-10-04 13:15:18 +02:00
if (!_.contains(active, promise.promiseId)) {
throw new BrokenPromiseError(promise.promiseId);
2014-10-02 00:30:25 +02:00
}
});
return promise;
}
function wait() {
var promises = arguments;
2014-09-04 18:06:25 +02:00
var deferred = jQuery.Deferred();
2014-10-02 00:30:25 +02:00
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
}
2014-10-02 00:30:25 +02:00
function abortAll() {
active = [];
2014-09-04 18:06:25 +02:00
}
2014-10-02 00:30:25 +02:00
function getActive() {
return active.length;
2014-09-04 18:06:25 +02:00
}
return {
make: make,
wait: wait,
2014-10-02 00:30:25 +02:00
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);