kriskowal / q

A promise library for JavaScript
MIT License
14.94k stars 1.21k forks source link

q.allDone - a combination of q.all and q.allSettled #723

Open pmeijer opened 9 years ago

pmeijer commented 9 years ago

Although it's pretty straightforward to monkey path the library, I've noticed a need for a function like the one below.

/**
 * A combination of q.allSettled and q.all. It works like q.allSettled in the sense that
 * the promise is not rejected until all promises have finished and like q.all in that it
 * is rejected with the first encountered rejection and resolves with an array of "values".
 *
 * The rejection is always an Error.
 * @param promises
 * @returns {*|promise}
 */
q.allDone = function (promises) {
    var deferred = q.defer();
    q.allSettled(promises)
        .then(function (results) {
            var i,
                values = [];
            for (i = 0; i < results.length; i += 1) {
                if (results[i].state === 'rejected') {
                    deferred.reject(new Error(results[i].reason));
                    return;
                } else if (results[i].state === 'fulfilled') {
                    values.push(results[i].value);
                } else {
                    deferred.reject(new Error('Unexpected promise state ' + results[i].state));
                    return;
                }
            }
            deferred.resolve(values);
        });

    return deferred.promise;
};
ramongilmoreno commented 7 years ago

I find this useful. I have it as a common utility in my projects.