While loops using Await Async.

强颜欢笑 提交于 2019-12-04 10:11:48

问题


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++
  }

What I think it does is this:

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...} 
      }
   }
  }
})

If that's totally false could you show another way to do it with async await + while loop?

Thanks!!


回答1:


Is it the correct way to use while loops with asynchronous conditions?

Yes. async functions simply suspend their execution on every await until the respective promises fulfills, and any control structures continue to work as before.




回答2:


Yep, it's fine to do it like this:

    let stopped = false

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



回答3:


Its been awhile since this question was asked. I am new to js after many years of other languages (starting with punch cards and paper tape) and needed to solve this problem. Here is my answer:

var loopContinue = true;
var n = 0;

async function  Managework() {
  while (loopContinue) {  //seemingly an infinite loop
    //await (doWork(n));
    await (doWork(n).catch(() => { loopContinue=false; }));
    n++;
    console.log(`loop counter ${n}`);
  }
  console.log(`loop exit n=${n} loopContinue=${loopContinue}`);
 }

Managework();

function doWork(n) {
 return new Promise((resolve, reject) => {
    console.log(`dowork(${n})`);
    if (n > 5) {
      //loopContinue = false;
      reject(`done`);
    }
    setTimeout(() => {
      resolve('ok');
    }, 1000);
  });
}

As desired the loop breaks after the 5th iteration. 'loopContinue' global can either be set in the work function or in the catch (or could be the then) of the promise. I tired just using 'break' in the then or catch but I get an error.

If you want to do it in doWork you can eliminate the catch and and just call doWork() and uncomment the // loopContinue= false in doWork. Either way works. This was tested with node.js

I found stuff on nextTick but this seems much easier.



来源:https://stackoverflow.com/questions/39110762/while-loops-using-await-async

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!