0

Example:

  • OUTER async function
    • INNER async function
      • await call()

I can see that the OUTER does not await for an await call from the INNER. But can somebody explain this to me so I can fully understand why it works like that?

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();
cbdeveloper
  • 27,898
  • 37
  • 155
  • 336

0 Answers0