Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript async/await in a generic loop

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 )

}` 
like image 825
leonard vertighel Avatar asked Apr 19 '26 18:04

leonard vertighel


1 Answers

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();
}
like image 114
Bergi Avatar answered Apr 21 '26 07:04

Bergi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!