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.
source share