有人可以幫我解釋一下為什么它會這樣嗎?
據我所知,await sleep(1)在這種情況下添加該行不應該影響代碼流。但是,確實如此。
function sleep(time) {
return new Promise((r) => setTimeout(r, time));
}
async function test(target) {
const ids = { a: ['a1', 'a2'], b: ['b3', 'b4'] }[target];
for (id of ids) {
console.log('X.', target, id);
// await sleep(1);
console.log('Y.', target, id);
}
}
test('a');
test('b');


為什么?
謝謝!
uj5u.com熱心網友回復:
嘗試使用for (const id of ids) {. 沒有constor let,您是id在全域范圍內定義。
function sleep(time) {
return new Promise((r) => setTimeout(r, time));
}
async function test(target) {
const ids = { a: ['a1', 'a2'], b: ['b3', 'b4'] }[target];
for (const id of ids) {
console.log('X.', target, id);
await sleep(1);
console.log('Y.', target, id);
}
}
test('a');
test('b');
uj5u.com熱心網友回復:
你不是等著test('a')完成。
當test('b')到達,test('a')仍在運行(因為它是一個異步函式)。如果您希望它在開始另一個使用之前完成.then():
test('a').then(()=>test('b'));
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/322683.html
標籤:javascript 循环 异步等待
