获得第一个兑现的承诺 [英] Get first fulfilled promise

查看:19
本文介绍了获得第一个兑现的承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有两个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的极性,然后可以使用Promise.all,因为它在第一个被拒绝的promise上拒绝,即反转后对应于第一个实现的承诺:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆