While循环使用Await Async. [英] While loops using Await Async.

查看:1888
本文介绍了While循环使用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...} 
      }
   }
  }
})

如果这完全是错误的,您可以显示另一种使用异步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 functions 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆