Home > Software engineering >  Multiple awaits in for loop how to fix?
Multiple awaits in for loop how to fix?

Time:03-22

I have a for loop with multiple awaits and have no idea how to Promise.all each one so that I can remove the "Unexpected await inside a loop" esLint error. I have seen examples of fixes with Promise.all but it is for only 1 await. My loop has 3 awaits. Here is my code:

for (let i = 0; i < a.length; i  ) {
    let b = await http.get(...)
    let c = await http.get(...)
    await doSomethingElse(i, b, c);
}

how do I remove all the awaits? without doing so my whole function will fail

CodePudding user response:

You can Promise.all:

  • Each iteration of the loop
  • The requests for b and c, because neither is dependent on the other
Promise.all(
    a.map(
        (_, i) => Promise.all([
            http.get(...), // gets b
            http.get(...), // gets c
        ])
            .then(([b, c]) => doSomethingElse(i, b, c))
    )
)
    .then(() => {
        // everything is finished
    });
  • Related