0

here is my code.and its blocking. first its wait for some time then output the result. is there any way to write it non blocking so that output be like expected output output : 499999999067109000 4950 45 tick tick tick tick ...

expected Output be something like this: tick tick 45 tick tick ... 4950 tick tick tick .... 499999999067109000 tick tick ...

setImmediate(function(){
    myCalc(1000000000).then(console.log).catch(console.error);
});

setImmediate(function(){
    myCalc(100).then(console.log).catch(console.error);
});

setImmediate(function(){
    myCalc(10).then(console.log).catch(console.error);
});

setInterval(function(){
  console.log("tick");
},100);

function myCalc(n){
  return new Promise((resolve, reject)=>{
    try{
      sum =0;
      for(let i=0;i<n;i++){
        sum += i;
      }
      resolve(sum);
    }catch(err){
      reject(err);
    }
  });
}
  • Hi sanyaj, Node js is about non blocking IO not non blocking calculations, its not possible – Janith Sep 21 '18 at 13:49
  • What happens here is each event will be registered into the event loop, then first calculation will happen (and this is blocking), the respective calculations will happen. After that only the timeout events will fire. If this was a non blocking IO the non blocking may happen. – Janith Sep 21 '18 at 13:51
  • @Quentin Can you be more specific about which answer addresses this question? That target is a poorly asked question and doesn't seem to be useful in this context. – E_net4 Sep 21 '18 at 13:56
  • Please follow this [article](https://medium.com/@janithkasun/javascript-what-is-non-blocking-i-o-a2acb5b7594c) – Janith Sep 21 '18 at 13:57
  • @E_net4 — https://stackoverflow.com/a/51129437/19068 for example – Quentin Sep 21 '18 at 14:01
  • 1
    @E_net4 I concur, I was in the middle of writing an answer on the *why* and then would've went on to explain the *how* but the question was closed too quick. I think for the OP needs to understand the problem before they can solve it. – James Sep 21 '18 at 14:03
  • @James Indeed, at this point it might be best to let the OP provide additional information, including whether multi-threading is an option. – E_net4 Sep 21 '18 at 14:04

0 Answers0