I'm trying to understand promises properly.
I have a sleep function to which if I pass a time, it executes it with a delay. I want to execute everything in Sequence.
Problem:
1: However, sometimes my done is getting called even before the promise is full filled. Can someone explain me where is the bug in my code?
2: Can I use async await instead of promises here? if yes how?
My attempt:
/* Do the following:
2- creating sequential promise, by wait for 1s, 2s and 3s sequentially. And showing result for each promise is done.
3- creating parallel promise, by wait for 1s, 2s and 3s parallelly. And showing result when all promise is done.
4- creating mixed promise, by wait 1s, 2s squentially, after then wait for 3s, 4s, 5s parallelly.
5- createing sequential promise, by wait for 1s, undefined and 3s sequentially. catch the error.
6- createing sequential promise, by wait for 5 different numbers, with random number as input.
*/
// Sleep takes time and returns time+1
const sleep = (time) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log(`Resolving: ${time}+1`);
resolve(time+1);
}, time*1000);
});
}
// Generate Random number within a range.
const randomNumber = (min=1, max=8) => {
return Math.floor(Math.random() * (max-min+1) + min);
} // -5~5
console.log(
sleep(randomNumber())
.then(sleep(randomNumber()))
.then(sleep(randomNumber()))
.then(sleep(randomNumber()))
.then(sleep(randomNumber()))
.then((e)=> {
console.log("Done", e); // Done called when all promises are done.
})
)