了解promise.race()用法 [英] Understanding promise.race() usage
问题描述
据我所知, 承诺
:
好的,我知道 promise.all()
是什么。它并行运行promises,并且 .then
为两个值提供成功解析的值。这是一个例子:
Ok, I know what promise.all()
does. It runs promises in parallel, and .then
gives you the values if both resolved successfully. Here is an example:
Promise.all([
$.ajax({ url: 'test1.php' }),
$.ajax({ url: 'test2.php' })
])
.then(([res1, res2]) => {
// Both requests resolved
})
.catch(error => {
// Something went wrong
});
但我不明白 promise.race()
应该做的确切吗?换句话说,不使用它有什么区别?假设:
But I don't understand what does promise.race()
is supposed to do exactly? In other word, what's the difference with not using it? Assume this:
$.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()
?
See? I haven't used promise.race()
and it behaves like promise.race()
. Anyway, is there any simple and clean example to show me when exactly should I use promise.race()
?
推荐答案
如您所见, race()
将返回首先解决或拒绝的promise实例:
As you see, the race()
will return the promise instance which is firstly resolved or rejected:
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
});
对于要使用的场景,您可能希望限制请求的成本时间:
For a scenes to be used, maybe you want to limit the cost time of a request :
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([])
首先返回,
With the race()
you just need to get the returned promise, you needn't care about which one of the promises in the race([])
firstly returned,
然而,如果没有种族
,就像你的例子一样,你需要关心哪一个将首先返回,并在 success
回调中调用回调。
However, without the race
, just like your example, you need to care about which one will firstly returned, and called the callback in the both success
callback.
这篇关于了解promise.race()用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!