szurubooru/public_html/js/Promise.js

58 lines
1.1 KiB
JavaScript
Raw Normal View History

2014-09-04 18:06:25 +02:00
var App = App || {};
2014-10-02 00:30:25 +02:00
App.Promise = function(_, jQuery) {
2014-09-04 18:06:25 +02:00
2014-10-02 00:30:25 +02:00
var active = [];
function make(callback) {
var deferred = jQuery.Deferred();
var promise = deferred.promise();
callback(function() {
deferred.resolve.apply(deferred, arguments);
active = _.without(active, promise);
}, function() {
deferred.reject.apply(deferred, arguments);
active = _.without(active, promise);
});
promise.then(function() {
if (!_.contains(active, promise)) {
throw new Error('Broken promise');
}
});
active.push(promise);
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
2014-10-02 00:30:25 +02:00
App.DI.registerSingleton('promise', ['_', 'jQuery'], App.Promise);