在forEach循环中嵌套了异步函数。为什么外部函数不等待内部函数的等待调用?

时间:2019-12-07 12:22:58

标签: javascript asynchronous async-await

示例:

  • 外部异步功能
    • 内部异步功能
      • 等待呼叫()

我可以看到 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();

0 个答案:

没有答案