简体   繁体   English

一般循环中的javascript async / await

[英]javascript async/await in a generic loop

I want to make this example https://stackoverflow.com/a/33585993/1973680 synchronous. 我想让这个例子https://stackoverflow.com/a/33585993/1973680同步。

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: myfunc本身就是一个异步函数,等待各种其他函数:

async myfunc(params,cb){

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

}` 

Is this the correct implementation? 这是正确的实施吗?

Yes. 是。 await works in loops like you'd expect it to, if that was your actual question. 如果那是你的实际问题, await就像你期望的那样在循环中工作。
I would however recommend to write 不过我会建议写

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM