skip to Main Content

I am learning JavaScript and just went over Promises. I tried to write a loop that looked similar to this:

for (let i of someArray) {
   if (condition) {
      await returnsPromise(i)
   }
}

This code does not work, and I was wondering if there is any other syntax that I would have to be aware of.

2

Answers


  1. To use await inside a loop, you need to define an async function and then call it within that function.

    async function loop() {
      for (let i of someArray) {
        if (condition) {
          await returnsPromise(i)
        }
      }
    }
    
    loop();
    Login or Signup to reply.
  2. the await code must still require the async function as a caller. or you can use deno.js then your code will work fine. no need for async function anymore.
    try my code it works fine

    function returnsPromise(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }
    async function loop(someArray){
      for (let i of someArray) {
        if (true) { // condition
          console.log(await returnsPromise(i), i)
        }
       }
     }
    loop([500,1000, 2000])
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search