得到第一个履行的承诺

如果我有两个承诺A和B,其中只有一个承诺会成功,我怎样才能获得成功的承诺? 我正在寻找类似于Promise.race东西,但是它只会返回满足的第一个承诺。 我正在使用ES6的承诺。

反转承诺的极性,然后你可以使用Promise.all ,因为它拒绝了第一个被拒绝的承诺,这个承诺在倒置之后就相当于第一个履行的承诺:

 const invert = p => new Promise((res, rej) => p.then(rej, res)); const firstOf = ps => invert(Promise.all(ps.map(invert))); // Utility routines used only in testing. const wait = ms => new Promise(res => setTimeout(() => res(ms), ms)); const fail = f => Promise.reject(f); const log = p => p.then(v => console.log("pass", v), v => console.log("fail", v)); // Test. log(firstOf([wait(1000), wait(500) ])); log(firstOf([wait(1000), fail("f1")])); log(firstOf([fail("f1"), fail("f2")])); 

如果你想要第一个成功解决的承诺,而你想忽略之前的任何拒绝,那么你可以使用这样的东西:

 // 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); } }); }); }); } 

我没有看到你如何使用Promise.race() ,因为它只是报告第一个承诺完成,如果第一个承诺拒绝,它会报告拒绝。 所以,在你的问题中,你所问的并不是你要问的问题,那就是要报告解决的第一个承诺(即使在它之前完成了一些拒绝)。

FYI, 蓝鸟承诺库有Promise.some()Promise.any() ,可以为你处理这个案例。

  //example 1 var promise_A = new Promise(function(resolve, reject) { // выполнить что-то, возможно, асинхронно… setTimeout(function(){ return resolve(10); //return reject(new Error('ошибка')) },10000) }); var promise_B = new Promise(function(resolve, reject) { // выполнить что-то, возможно, асинхронно… setTimeout(function(){ return resolve(100); },2000) }); /* //[100,10] Promise.all([ promise_A,promise_B ]).then(function(results){ console.log(results) }); */ //100 Promise.race([ promise_A,promise_B ]).then(function(results){ console.log(results) });