Home > database >  For Loop with a function call doesn't seem to be waiting for await inside the function
For Loop with a function call doesn't seem to be waiting for await inside the function

Time:12-02

Sorry about the confusing title. So what I basically have is a function with a for-loop, calling another function in the loop, which has a call with an 'await' inside it. the function inside pushes values into an array once the async/await call is done. The value of the array is then returned once the loop is complete.

Something like this:


let globalArray = [];

const innerFunction = () => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(1);
    }, 100);
  });
};

const callingFunction = async () => {
  let a = await innerFunction();
  globalArray.push(a);
  console.log(`GLOBAL ARRAY AFTER PUSH IN THE CALLING FUCNTION`);
  console.log(globalArray);
};


const outerFunction = () => {
  for (let i = 0; i < 1; i  ) {
    callingFunction();
    console.log(`GLOBAL ARRAY AFTER FUCTION CALL`);
    console.log(globalArray);
  }
  console.log(`GLOBAL ARRAY AFTER FOR LOOP END ${globalArray}`);
  console.log(globalArray);
};

What I have observed is that the value of globalArray does not change in the logs both inside and right after the for loop (logs globalArray as []), but the log inside the callingFunction right after the push statement seems to log globalArray as [1].

This would indicate that the await statement isn't being waited upon by the primary function call in the for loop.

Ideally, I would expect all the log statements to log globalArray as [1].

Why would this be happening? Is there a better way to do this? I can't change the call pattern per se, because in my actual implementation, each function has additional things to do.

I've put this implementation up on stackblitz here: https://stackblitz.com/edit/typescript-i8jusx?file=index.ts

CodePudding user response:

You are missing the await keyword in outerFunction when calling callingFunction.

const outerFunction = async () => {
  for (let i = 0; i < 1; i  ) {
    await callingFunction();
    console.log(`GLOBAL ARRAY AFTER FUCTION CALL`);
    console.log(globalArray);
  }
  console.log(`GLOBAL ARRAY AFTER FOR LOOP END ${globalArray}`);
  console.log(globalArray);
};

Remember that an async function automatically returns a Promise, even if it is Promise<void>

  • Related