為什么會發生這種行為Promise.race()
,即 Promise.resolve(1) 計算得更快,而不僅僅是 2?
Promise.race([Promise.resolve(1), 2]).then(console.log)
uj5u.com熱心網友回復:
來自MDN 檔案
如果可迭代物件包含一個或多個非承諾值和/或已確定的承諾,則 Promise.race 將確定為陣列中找到的這些值中的第一個
const foreverPendingPromise = Promise.race([]);
const alreadyFulfilledProm = Promise.resolve(100);
const arr = [foreverPendingPromise, alreadyFulfilledProm, "non-Promise value"];
const arr2 = [foreverPendingPromise, "non-Promise value", Promise.resolve(100)];
const p = Promise.race(arr);
const p2 = Promise.race(arr2);
console.log(p);
console.log(p2);
setTimeout(() => {
console.log("the stack is now empty");
console.log(p);
console.log(p2);
});
// logs, in order:
// Promise { <state>: "pending" }
// Promise { <state>: "pending" }
// the stack is now empty
// Promise { <state>: "fulfilled", <value>: 100 }
// Promise { <state>: "fulfilled", <value>: "non-Promise value" }
uj5u.com熱心網友回復:
基本上,Promise.race
隱Promise.all
式呼叫Promise.resolve
引數,而 1 就在 2 之前。
then
這對于從回呼回傳的值、您和其他幾個地方回傳的值也是如此,await
其想法是更容易在 promise 和 non-promise 代碼之間進行互操作。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/508484.html
標籤:javascript 异步 承诺 es6-承诺
上一篇:反應鉤子中的異步等待承諾拒絕