了解 promise.race() 用法

新手上路,请多包涵

据我所知,关于 promise 有两个选项:

好的,我知道 promise.all() 的作用。它并行运行承诺,并且 .then 为您提供值(如果两者都已成功解决)。这是一个例子:

 Promise.all([
  $.ajax({ url: 'test1.php' }),
  $.ajax({ url: 'test2.php' })
])
.then(([res1, res2]) => {
  // Both requests resolved
})
.catch(error => {
  // Something went wrong
});

但我不明白 promise.race() 应该做什么?换句话说,不使用它有什么区别?假设这样:

 $.ajax({
    url: 'test1.php',
    async: true,
    success: function (data) {
        // This request resolved
    }
});

$.ajax({
    url: 'test2.php',
    async: true,
    success: function (data) {
        // This request resolved
    }
});

看?我没有使用 promise.race() 它的行为类似于 promise.race() 。无论如何,是否有任何简单明了的示例可以告诉我什么时候应该使用 promise.race()

原文由 Martin AJ 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 201
1 个回答

如您所见, race() 将返回首先解决或拒绝的承诺实例:

 var p1 = new Promise(function(resolve, reject) {
    setTimeout(resolve, 500, 'one');
});
var p2 = new Promise(function(resolve, reject) {
    setTimeout(resolve, 100, 'two');
});

Promise.race([p1, p2]).then(function(value) {
  console.log(value); // "two"
  // Both resolve, but p2 is faster
});

对于一个要使用的场景,也许你想限制一次请求的成本时间:

 var p = Promise.race([
    fetch('/resource-that-may-take-a-while'),
    new Promise(function (resolve, reject) {
         setTimeout(() => reject(new Error('request timeout')), 5000)
    })
])
p.then(response => console.log(response))
p.catch(error => console.log(error))

使用 race() 你只需要得到返回的承诺,你不需要关心 race([]) 中的哪个承诺首先返回,

但是,如果没有 race ,就像您的示例一样,您需要关心哪个将首先返回,并在两个 success 回调中调用回调。

原文由 JiangangXiong 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题