I trying to solve a challenge with the following question:
Implements a function that takes a number as a parameter and after x milliseconds (between an interval of 1 to 100 ms. Use setTimeout and as floor and random functions from the Math library), without a console or with twice the received parameter. Then, call this function 5 times. Ex.:
Without performing any treatment, it is easy to notice that the order of the values shown on the console is random and does not accept the order of calling the functions. Therefore, to resolve this issue, treat or subscribe to setTimeout using callback, Promise and async / waitit.
That's the expected behavior:
let result;
result = double(5, 0); // returns 10
result = double(12, result); // returns 34
result = double(2, result); // returns 38
The goal is to treat the asynchronous behavior of setTimeout with promises, async functions or callbacks. That's was what i got until now and with no success:
function promisify(number, increase){
return new Promise(resolve => setTimeout(() => resolve(number * 2 + increase), 100))
}
async function double(number, increase) {
const value = await promisify(number, increase);
return value;
}
let result;
result = double(5, 0)
result = double(10, result)
result = double(20, result)
console.log(result)
- I want to return a promise with a set timeout that was a random calculate miliseconds until resolve the double of the number + the increase value if it exists.
- Even waiting for the promise to result in the async function, it continues to return a pending promise
- The result variables have to increase on each calc but they're receiving functions instead of the double result