据我所知,关于promise
有两种选择:
好的,我知道 promise.all()
做了什么。它并行运行 promise ,如果两者都成功解决,.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()
?
最佳答案
如您所见,race()
将返回最先解决或拒绝的 promise 实例:
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()
你只需要得到返回的 promise,你不需要关心 race([])
中的哪个 promise 优先返回,
但是,如果没有race
,就像你的例子一样,你需要关心哪个先返回,并在两个success
回调中调用回调。
关于javascript - 了解 promise.race() 用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46376432/