3

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 )

}` 
Community
  • 1
  • 1
leonard vertighel
  • 1,058
  • 1
  • 18
  • 37
  • 2
    `async/await` doesn't make code synchronous. It just enables a more convenient way of writing asynchronous code. And yeah, that looks like it should work (why don't you just try it?), although I'd rather write `async () => await myfunc([1,2,3],err => err)`. – Felix Kling Dec 14 '16 at 00:19
  • 1
    What do you mean by "make synchronous"? Or is it a typo and you meant asynchronous? – Bergi Dec 14 '16 at 01:16
  • 1
    That `err => err` callback you are passing but not using anywhere does not look like correct usage of `async function`s. – Bergi Dec 14 '16 at 01:17

1 Answers1

10

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();
}
Bergi
  • 630,263
  • 148
  • 957
  • 1,375