Home > OS >  Why is my loop continuing without waiting for async/await to complete?
Why is my loop continuing without waiting for async/await to complete?

Time:12-16

So at a high level how I am expecting this to work.

  1. Function1 will be kicked off by a user.
  2. During the execution Function2 will be kicked off inside Function1.
  3. Function2 will be kicked off for every loop of an array.
  4. I need to wait for each Function2 to complete before moving on to the next loop.

Currently it is running Function2 the correct amount of times but it is not waiting for each previous to complete.

async function1() {

      let index = 0
      for (const row of this.submissions) {
        if (row.EXCEL_CHECK === 1) {
          (async() => {
            let indexAdd = await this.function2(index)
          })();
        }
        index = index   indexAdd
      }
}

  async function2(inlineIndex) {
  
    // Create someArray
     try {
      await this.getSomeArray(something);
    } catch (e) {
      console.log('Try/Catch Error: '   e);
    }
    let x = this.someArray.length - 1;
    return x;
    
  }

Note I only added the async arrow because I was getting this result when I tried just putting

let indexAdd = await function2(index)

Error:

'await' expressions are only allowed within async functions and at the top levels of modules.ts

Note I have simplified the functions for ease of explanation, but this call is being made deep in the function itself.

CodePudding user response:

Function1 is already an asynchronous function, so you don't need to wrap Function2 call with anonymous asynchronous arrow function.

So you can safely remove these:

// - (async() => {
    let indexAdd = await this.function2(index)
// - })();

CodePudding user response:

  await (async() => {
        let indexAdd = await this.function2(index)
  })();

Just add another await with anonymous function.

Or you remove the async totally as func 1 is already async

//(async() => {
    let indexAdd = await this.function2(index)
//})();

And Make sure func1 is called with await

await function1();
  • Related