获得第一个履行承诺 [英] Get first fulfilled promise
问题描述
如果我有两个承诺A和B,其中只有一个会成功,我怎样才能获得成功完成的任何承诺?我正在寻找类似于 Promise.race
的东西,但这只会返回第一个履行的承诺。我正在使用来自ES6的承诺。
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
, but which will return only the first promise that fulfills. I'm using promises from ES6.
推荐答案
反转承诺的极性,然后你可以使用 Promise.all
,因为它拒绝了第一个被拒绝的承诺,它在反转后对应于第一个履行的承诺:
Invert the polarity of the promises, and then you can use Promise.all
, because it rejects on the first rejected promise, which after inversion corresponds to the first fulfilled promise:
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")]));
这将返回第一个履行承诺的价值,或者如果全部拒绝,一系列拒绝原因。
This will return the value of the first fulfilled promise, or if all reject, an array of rejection reasons.
这篇关于获得第一个履行承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!