Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Multiple awaits in for loop how to fix?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
    });
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading