Search code examples
javascriptdeferreddeferred-execution

Need jQuery's "when" functionality for mpromise/mongoose


Is there such a thing as a when clause for mpromise/mongoose? I'm looking to do something lke this without having to write my own wrapper for mpromise.

$.when(jQueryPromise1,jQueryPromise3,jQueryPromise3).done(function(r1,r2,r3) {
    // success code
}.fail(function(err1,err2,err3) {
    //failure code
});

I realize chaining exists, that's not what I want. I'm looking for a mechanism in mpromise/mongoose that will execute when all promises have been completed.


Solution

  • Here's a sample implementation of when:

    function when(/* promise list */) {
        var promises = [].slice.call(arguments),
            whenPromise = new Promise,
            results = new Array(promises.length),
            remaining = promises.length,
            done = false,
            finish = function() {
                done = true;
            };
    
        whenPromise.onFulfill(finish).onReject(finish);
    
        promises.forEach(function(promise) {
            promise.onFulfill(function(result) {
                if (!done) {
                    // index of result should correspond to original index of promise
                    results[promises.indexOf(promise)] = result;
                    if (--remaining == 0) {
                        // fulfill when all are fulfilled
                        whenPromise.fulfill.apply(whenPromise, results);
                    }
                }
            }).onReject(function(err) {
                if (!done) {
                    // reject when one is rejected (a la jQuery)
                    whenPromise.reject(err);
                }
            });
        });
    }