0

I'm trying to understand how to use time consuming function with Promises. I have some nonsense, but time consuming function computation() (that I create for demonstration purpose), that would need 3-5 seconds to run:

function computation(n = 100000000) {
  let i = 0;
  let a = n;
  while (i < n) {
    a = i + Math.floor(2 / i);
    a -= (((i / ((a * 15) / a)) * 21) % n) - 1;
    i++;
  }
  return Math.floor(a);
}

console.log('1');

let p = new Promise(function (resolve, reject) {
  let a = computation();
  console.log(a);
  if (a % 2 == 1) {
    resolve("odd");
  }
  if (a % 2 == 0) {
    reject("even");
  }
});

console.log('2');


p.then(value => {console.log(value)}, value => {console.log(value)});

It outputs:

1 
60000001 
2 
odd

But I want:

1 
2 
60000001
odd

I tried to wrap the whole promise expression(let p = new Promise(...) in setTimeOut, but after it p is not recognizable, since its invoking .then() before Promise object is returned to p.

I want to be able to run such long functions without blocking JS runtime, and after its finished obtain its value with promise. In my example it should console.log(1), then console.log(2) and after computation() is done invoke p,then(). How can I put away calculation computation() from stack? I want to understand how to make it work with Promise usage, without async/await sugar.

  • 1
    Use a webworker. Async doesn't automatically make JS multi-threaded. – evolutionxbox Mar 23 '23 at 20:27
  • The main JS runtime is single threaded, so Promises will not give you a means of chunking up work. If you split the work into chunks you can [cobble something together](https://stackoverflow.com/a/16353623/21146235) with `setTimeout`, but as @evolutionxbox suggests [web workers](https://stackoverflow.com/a/50073877/21146235) are available for offloading exactly such computational work in a separate thread. – motto Mar 23 '23 at 20:30
  • "*how to use time consuming function with Promises*" - you don't. Promises are used for **asynchronous** tasks, to simplify dealing with them. They do not make blocking things asynchronous. – Bergi Mar 23 '23 at 20:31
  • Thanks all for your comments! I'll look into workers – VelikiyMalchik Mar 23 '23 at 20:48

0 Answers0