while循环使用Await Async.

Hch*_*nes 16 loops asynchronous while-loop async-await ecmascript-next

这个Javascript函数似乎以异步方式使用while循环.这是使用具有异步条件的while循环的正确方法吗?

 var Boo;
 var Foo = await getBar(i)
 while(Foo) {
    Boo = await getBar3(i)
    if (Boo) {
      // something
    }
    Foo = await getBar(i)
    i++
  }
Run Code Online (Sandbox Code Playgroud)

我认为它的作用是:

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...} 
      }
   }
  }
})
Run Code Online (Sandbox Code Playgroud)

如果那是完全错误的话你能用异步await + while循环显示另一种方法吗?

谢谢!!

Ber*_*rgi 17

这是使用具有异步条件的while循环的正确方法吗?

是.async function只需暂停执行,await直到相应的承诺完成,任何控制结构继续像以前一样工作.


RTW*_*RTW 12

是的,这样做很好:

    let stopped = false

    // infinite loop
    while(!stopped) {
       let res = await fetch('api link') 
       if (res.something) stopped = true // stop when you want
    }
Run Code Online (Sandbox Code Playgroud)

  • 一定要处理“something”总是 false 的情况,否则你的循环将保持无限。 (2认同)
  • 只能在异步函数中使用await (2认同)

Mar*_* An 9

这是在异步条件下使用 while 循环的正确方法吗?

是的前提是getBargetBar3是异步函数(标记为 async 或仅返回 a Promise)。

当然,执行应该在异步上下文中async函数内部)

我可以看到的一个可能的问题是,最初有 2 次执行getBar相同i,其余执行使用和i之间不匹配。如果这不是所需的行为,那么更正确的版本可能是:whileif

    (async ()=>{
     while(await getBar(i)) {    
        if (await getBar3(i)) {
          //do something
        }
        i++;
      }
    })();
Run Code Online (Sandbox Code Playgroud)

在此处查看模拟示例