最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript asyncawait in a generic loop - Stack Overflow

programmeradmin4浏览0评论

I want to make this example 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 )

}` 

I want to make this example https://stackoverflow./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 )

}` 
Share Improve this question edited May 23, 2017 at 11:46 CommunityBot 11 silver badge asked Dec 14, 2016 at 0:13 leonard vertighelleonard vertighel 1,0681 gold badge19 silver badges39 bronze badges 3
  • 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 Commented Dec 14, 2016 at 0:19
  • 1 What do you mean by "make synchronous"? Or is it a typo and you meant asynchronous? – Bergi Commented Dec 14, 2016 at 1:16
  • 1 That err => err callback you are passing but not using anywhere does not look like correct usage of async functions. – Bergi Commented Dec 14, 2016 at 1:17
Add a ment  | 

1 Answer 1

Reset to default 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 remend to write

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

评论列表(0)

  1. 暂无评论