在 Javascript 中使用 Promise all()、race()、allSettled() 和 any()

Promise有很多选项,可能看起来有点混乱。让我们详细看看Promise all()、race()、allSettled() 和 any()这些选项:

在 Javascript 中使用 Promise all()、race()、allSettled() 和 any()

Promise.all() - 仅当所有给定的promises都被解决时才执行。如果一个承诺失败,它会立即拒绝并返回第一个rejection消息。

Promise.all([getUserById(1),getUserById(2), getUserById(3)])
.then((users) => {
    // will  return all the users
})
.catch((error) => {
    // will fail when the first promise fails
});

Promise.allSettled() - 它将在所有给定的promises都已完成或被拒绝时执行。

Promise.allSettled([getUserById(1), getUserById(2), getUserById(3)])
.then((results) => {
    // the items in results can be either a user or an error
    // it waits for all the promises to have a result.
})

Promise.race() - 将在给定的并发promises中的第一个promises fulfills或rejects时解决。

Promise.race([getUserById(1), getUserById(2), getUserById(3)])
.then(([user]) => {
    // will return the first retrevied user
})
.catch((error) => {
    // will fail at the first rejected promise
});

Promise.any() - 一旦其中一个promises完成,它就会执行,但在完成所有promises之前它不会执行。它试图实现至少一个promise。

Promise.any([getUserById(1), getUserById(2), getUserById(3)])
.then(([user]) => {
    // will return the first retrevied user
})
.catch((error) => {
    // will fail only when all the promises have failed
});
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 xxx@163.com 举报,一经查实,本站将立刻删除。

发表评论

登录后才能评论