javascript - Calling function with a Promise hangs when in a loop -


when run following javascript code, works fine. if remove settimeout function call , replace line of code like:

resolve(x); 

the browser hang.

the browser appears hang because processing calls processnode function in endless while loop. isn't clear why there blocking going on @ all. processnode returns promise. furthermore, startnodeprocessing async function using await on calls. thought having promise , async function await prevent blocking of thread, i'm wrong. appears settimeout executes code on separate thread preventing blocking. if case, why bother promise or async function start with?

function processnode(x) {     return new promise(resolve => {         console.log("x: " + x + "  " + date.now());         settimeout(() => {             resolve(x);         }, x);     }); }  async function startnodeprocessing() {     while(true) {         var = processnode(1);         var b = processnode(1);         var c = processnode(1);         var d = processnode(1);         var a1 = await a;         var b1 = await b;         var c1 = await c;         var d1 = await d;     }      return; }  startnodeprocessing(); 

well following happens:

 var = processnode(1); //the parser jumps processnode , creates promise: return new promise(function(resolve) //the promise resolved resolve(x); //the function returns, enter main function again:        var a1 = await a; //await internally calls function: a1.then(return func) //as promise resolved, callback called immeadiately //the parser returns main function 

as can see, parser never exits loop, therefore blocking never halts.


Comments

Popular posts from this blog

python Tkinter Capturing keyboard events save as one single string -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

javascript - Z-index in d3.js -