0

I have a function which is doing a heavy job so I decided to run this function asynchronously and prevent browser freezing when my function is running however after I add promise to my function nothing happened and browser still freeze until function works done. so I simulate my function heavy job with a simple for loop and add some extra useless code inside that for loop in order to prevent javascript engine skip for loop.so after I run the code it turns out for loop doesn't run asynchronously so what is wrong here?

here is sample code simulate my problem:

new Promise(resolve =>{
  //some heavy task
  for(let i=0 ; i<10000; i++){
      if(i % 2 == 0){
          console.log(i);
      }
  }
  resolve();
}).then(()=>{
  console.log("finished")
})
console.log("javascript engine should continue running");

So in my idea first the last line console log must runs because javascript should push that promise into event queue and after all that logs inside that for loop printed finally finished should be printed however it isn't the case.

Daniel.V
  • 2,322
  • 7
  • 28
  • 58
  • 3
    Using promises won't solve the problem - the code still will run in the same thread as the rest of the JavaScript. To make it run truly in parallel, you'll need to employ workers. https://developer.mozilla.org/en-US/docs/Web/API/Worker – mbojko Oct 04 '19 at 13:36
  • `Promise.resolve().then(resolve =>{ //some heavy task for(let i=0 ; i<10000; i++){ if(i % 2 == 0){ console.log(i); } } console.log("finished") }); console.log("javascript engine should continue running");` – Alex Vovchuk Oct 04 '19 at 14:08
  • new Promise doesn't start new task by itself. New task being started either after resolve() or after asynchronous code inside promise. Use solution from my post above: https://jsfiddle.net/zordaxy/p8crm5se/ – Alex Vovchuk Oct 04 '19 at 14:09

0 Answers0