javascript async/await in a generic loop

2.5k views Asked by At

I want to make this example https://stackoverflow.com/a/33585993/1973680 synchronous.

Is this the correct implementation?

        let times= async (n,f)=>{while(n-->0) await f();} 

        times(5,()=>
               myfunc([1,2,3],err => err)
              )

myfunc is itself an async function awaiting for various other functions:

async myfunc(params,cb){

   await a( err => err )
   await b( err => err )
   await c( err => err )

}` 
1

There are 1 answers

0
Bergi On BEST ANSWER

Is this the correct implementation?

Yes. await works in loops like you'd expect it to, if that was your actual question.
I would however recommend to write

async function times(n, f) {
    while (n-- > 0)
        await f();
}