Get first fulfilled promise

前端 未结 5 1800
遥遥无期
遥遥无期 2020-12-06 02:44

If I have two promises A and B, only one of which will succeed, how can I get whichever one fulfills successfully? I\'m looking for something similar to Promise.race

5条回答
  •  被撕碎了的回忆
    2020-12-06 03:06

    If you want the first promise that resolves successfully and you want to ignore any rejections that come before that, then you can use something like this:

    // returns the result from the first promise that resolves
    // or rejects if all the promises reject - then return array of rejected errors
    function firstPromiseResolve(array) {
        return new Promise(function(resolve, reject) {
            if (!array || !array.length) {
                return reject(new Error("array passed to firstPromiseResolve() cannot be empty"));
            }
            var errors = new Array(array.length);
            var errorCntr = 0;
            array.forEach(function (p, index) {
                // when a promise resolves
                Promise.resolve(p).then(function(val) {
                    // only first one to call resolve will actually do anything
                    resolve(val);
                }, function(err) {
                    errors[index] = err;
                    ++errorCntr;
                    // if all promises have rejected, then reject
                    if (errorCntr === array.length) {
                        reject(errors);
                    }
                });
            });
        });
    }
    

    I don't see how you can use Promise.race() for this because it simply reports the first promise to finish and if that first promise rejects, it will report a rejection. So, it is not doing what you asked in your question which is to report the first promise that resolves (even if some rejections finished before it).

    FYI, the Bluebird promise library has both Promise.some() and Promise.any() which can handle this case for you.

提交回复
热议问题