While loops using Await Async.

后端 未结 4 1686
旧时难觅i
旧时难觅i 2020-12-29 04:24

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         


        
4条回答
  •  粉色の甜心
    2020-12-29 04:42

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

    Yes, provided that getBar and getBar3 are asynchronous functions (marked as async or just returning a Promise).

    Of course the execution should be inside an asynchronous context (inside async function)

    A possible issue that I can see is that initially there are 2 executions of getBar with the same i and the rest of executions use a mismatched i between while and if. If this is not the desired behavior perhaps a more correct version would be:

        (async ()=>{
         while(await getBar(i)) {    
            if (await getBar3(i)) {
              //do something
            }
            i++;
          }
        })();
    

    See a mocked example here

提交回复
热议问题