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.