wait函式被用作睡眠函式,fn函式接受一個陣列(items),它記錄每個專案并在記錄下一個專案之前睡眠一秒鐘。
const wait = async(time)=> {
return new Promise((resolve) => setTimeout(resolve, time))
}
const fn = async( items) => {
for ( item of items) {
await wait(1000)
console.log( item)
}
}
const exeAll = async() => {
Promise.all([
fn(['A1', 'A2']) 。
fn(['B1', 'B2']) 。
])
}
exeAll()
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
問題在于exeAll函式所提供的結果,它列印出:
B1
A2
B2
B2
但我認為它應該列印成這樣:
A1
B1
A2
B2
執行上述代碼時,A1根本沒有顯示。誰能解釋一下原因?
uj5u.com熱心網友回復:
for (item of items) {將創建一個隱含的全域變數item,也就是說,多次呼叫fn將相互干擾,覆寫item。
const wait = async(time)=> {
return new Promise((resolve) => setTimeout(resolve, time))
}
const fn = async( items) => {
for (let item of items) {
//^^^^。
await wait(1000)
console.log( item)
}
}
const exeAll = async() => {
Promise.all([
fn(['A1', 'A2']) 。
fn(['B1', 'B2']) 。
])
}
exeAll()
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
我們可以添加更多的日志。
我們可以給fn添加更多的日志,看看在你的情況下會發生什么:
const wait = async(time)=> {
return new Promise((resolve) => setTimeout(resolve, time))
}
let counter = 0;
const fn = async( items) => {
const c = counter ;
console.log(`enter fn call #${c}`) 。
for ( item of items) {
console.log(`fn call #${c} sets item <-`, item);
await wait(1000)
console.log(`fn call #${c} reads item ->`, item) 。
console.log( item)
}
}
const exeAll = async() => {
Promise.all([
fn(['A1', 'A2']) 。
fn(['B1', 'B2']) 。
])
}
exeAll()
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
嚴格模式("use strict";)會發現這個錯誤,因為向一個未宣告的變數賦值會引發錯誤。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/318058.html
標籤:
