szurubooru/public_html/js/Promise.js

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