javascript - How to logically code an ES6 promise inside a while loop -
this code calls function (gettable()) returns promise:
function gettables() { while (mlobby.tblcount() < 4) { gettable().then(function(response) { mlobby.addtable(response); }, function (error) { console.error("gettable() finished error: " + error); }); } } it never resolves (and crashes due full memory) because of clash of async function call , normal flow of while loop. tried changing while if recursive call, gave same result:
function gettables() { if (mlobby.tblcount() < 4) { gettable().then(function(response) { mlobby.addtable(response); gettables(); } }); }
in experience, using promises inside of synchronous action while won't work want.
what i've done use async await accomplish same task. like...
async function gettables() { while (mlobby.tblcount() < 4) { await gettable(); // whatever other code need... } } so, while loop continue work expected after each gettable() call resolved. test code, obviously.
here's simple working example of i'm talking about: https://codepen.io/alexmacarthur/pen/rlwwno?editors=1011
Comments
Post a Comment