我剛開始探索ES6 async/await
,我發現一些真正的驚喜me.Basically,forEach
表現異步而for
循環表現同步這裏例如陣列在foreach是異步比較正常的循環
function getData(d) {
return new Promise((resolve,reject)=>{
setTimeout(()=>{
resolve(d.x+" %%%% ")
},1000)
})
}
const data=[{x:"aaa"},{x:"bbb"}]
//async for loop
const makeRequest1 = async() => {
for (let i in data){
let value=data[i]
console.log(value)
value.p=await getData(value)
console.log(JSON.stringify(value)+ ' after')
}
// console.log(rr)
console.log(data)
console.log("Is it block ??")
return "done"
}
// { x: 'aaa' }
// {"x":"aaa","p":"aaa %%%% "} after
// { x: 'bbb' }
// {"x":"bbb","p":"bbb %%%% "} after
// [ { x: 'aaa', p: 'aaa %%%% ' }, { x: 'bbb', p: 'bbb %%%% ' } ]
// Is it block ??
// done
//async for loop
const makeRequest2 = async() => {
data.forEach(async (value)=>{
console.log(value)
value.p=await getData(value)
console.log(JSON.stringify(value)+ ' after')
})
console.log(data)
console.log("Is it block ??")
return "done"
}
// { x: 'aaa' }
// { x: 'bbb' }
// [ { x: 'aaa' }, { x: 'bbb' } ]
// Is it block ??
// done
// {"x":"aaa","p":"aaa %%%% "} after
// {"x":"bbb","p":"bbb %%%% "} after
makeRequest2().then((r)=>{
console.log(r)
})
我知道for
和forEach
版本應該同步運行,在這種情況下forEach
怎麼會變成異步?
也許是因爲在回調前的'async' ... – Weedoze
@Weedoze很有可能,是否有任何詳細的解釋 – Guigui
您是說您正在探索'async'和'await',然後閱讀文檔。這會給你解釋 – Weedoze