我遇到了兩種常見的異步/等待 JavaScript 代碼樣式:
for await (const a of [x1, x2, x3, x4])
{
//do stufF
}
和
[x1, x2, x3, x4].forEach(async (a) {
//do stuff
}
這些中的任何一個是否有任何性能(或其他)優勢?
編輯:假設每個實體x
都是一個承諾。
uj5u.com熱心網友回復:
在 promise 完成之前,for 回圈不會繼續回圈中的下一個條目。
forEach 回圈將立即觸發您為每個 Promise 傳遞給它的異步函式,并且假設您await
在該函式中使用了 Promise,它將進入睡眠狀態,直到 Promise 解決。
鑒于您的變數包含承諾,無論他們正在做什么作業都已經在并行完成,所以這里唯一的決定因素是您是否想按順序或盡快繼續他們的處理。
(async function() {
const x1 = new Promise(r => setTimeout(() => {
console.log('Resolve x1');
r("x1")
}, 3500));
const x2 = new Promise(r => setTimeout(() => {
console.log('Resolve x2');
r("x2")
}, 4000));
const x3 = new Promise(r => setTimeout(() => {
console.log('Resolve x3');
r("x3")
}, 3000));
const x4 = new Promise(r => setTimeout(() => {
console.log('Resolve x4');
r("x4")
}, 2000));
for await (const a of [x1, x2, x3, x4]) {
console.log(`${a} available inside loop`);
}
})();
(async function() {
const x1 = new Promise(r => setTimeout(() => {
console.log('Resolve x1');
r("x1")
}, 3500));
const x2 = new Promise(r => setTimeout(() => {
console.log('Resolve x2');
r("x2")
}, 4000));
const x3 = new Promise(r => setTimeout(() => {
console.log('Resolve x3');
r("x3")
}, 3000));
const x4 = new Promise(r => setTimeout(() => {
console.log('Resolve x4');
r("x4")
}, 2000));
[x1, x2, x3, x4].forEach(async function (a) {
const value = await a;
console.log(`${value} available inside loop`);
});
})();
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/498340.html
標籤:javascript 表现 for循环 异步 异步等待