While 循环使用 Await Async. [英] While loops using Await Async.
问题描述
这个 Javascript 函数似乎以异步方式使用了 while 循环.在异步条件下使用 while 循环是否正确?
This Javascript function seems to use the while loop in an asynchronous way. Is it the correct way to use while loops with asynchronous conditions?
var Boo;
var Foo = await getBar(i)
while(Foo) {
Boo = await getBar3(i)
if (Boo) {
// something
}
Foo = await getBar(i)
i++
}
我认为它的作用是:
var Boo;
var Foo;
getBar(i).then( (a) => {
Foo = a;
if(Foo) {
getBar3(i).then( (a) => {
Boo = a
if(Boo) {
//something
i++;
getBar(i).then( (a} => { Repeat itself...}
}
}
}
})
如果那是完全错误的,您能否展示另一种使用 async await + while 循环来做到这一点的方法?
If that's totally false could you show another way to do it with async await + while loop?
谢谢!!
推荐答案
在异步条件下使用 while 循环是否正确?
Is it the correct way to use while loops with asynchronous conditions?
是的.async function
只是在每个 await
上暂停它们的执行,直到相应的承诺实现,并且任何控制结构都像以前一样继续工作.
Yes. async function
s simply suspend their execution on every await
until the respective promises fulfills, and any control structures continue to work as before.
这篇关于While 循环使用 Await Async.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!