示例:
我可以看到 OUTER没有等待来自INNER的等待呼叫。但是有人可以向我解释一下,这样我就可以完全理解为什么这样工作了?
const someArray = [
{foo: 'bar1'},
{foo: 'bar2'},
{foo: 'bar3'}
];
function callMockAPI_1() {
return new Promise((resolve,reject) => {
setTimeout(()=>resolve(someArray),500);
});
}
function callMockAPI_2(item,delay) {
return new Promise((resolve,reject) => {
setTimeout(()=>resolve('API_2 responded: ' + item.foo),delay);
});
}
async function main() { // OUTER ASYNC FUNC
console.log('Calling mockAPI_1...');
const myArray = await callMockAPI_1();
myArray.forEach(async (item) => { // INNER ASYNC FUNC
const newItem = {...item};
console.log('This is item: ' + item.foo);
if (item.foo === 'bar1') {
const result = await callMockAPI_2(newItem,1500); // INNER AWAIT CALL
console.log(result);
}
else if (item.foo === 'bar2') {
const result = await callMockAPI_2(newItem,1000); // INNER AWAIT CALL
console.log(result);
}
else if (item.foo === 'bar3') {
const result = await callMockAPI_2(newItem,500); // INNER AWAIT CALL
console.log(result);
}
});
}
main();