While loops use Await Async.

This Javascript function seems to use a while loop in asynchronous mode. Is it correct to use 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++ } 

I think so:

 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 this is completely false, can you show another way to do it with async wait + while while?

Thanks!!

+6
source share
2 answers

Is it correct to use loops with asynchronous conditions?

Yes. async function simply suspend their execution on each await until the corresponding promises execute, and all control structures continue to work as before.

+8
source

Some time has passed since this question was asked. I am new to js after many years of other languages ​​(starting with punched 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); }); } 

At will, the cycle is interrupted after the 5th iteration. The global loopContinue loop can either be set in the working function, or in the catch (or maybe then) promise. I'm tired of just using a β€œbreak” at that or catch, but I get an error.

If you want to do this in doWork, you can eliminate catch and just call doWork () and uncomment // loopContinue = false in doWork. Anyway. This has been tested with node.js

I found stuff on nextTick, but it seems a lot easier.

0
source

All Articles