I am trying to learn how to chain promise with JS. I saw the code here and they did it with a forloop JavaScript ES6 promise for loop. I found it to be cool and decided to try it with small adjustments. But it failed to work. I will really appreciate it if you can tell me why this doesn't work
Here's my code:
//Goal: print from 0-10 in order at random times
function test() {
for (let i = 0, p = Promise.resolve(); i < 10; i++) {
p = p.then(createPromise(i));
}
}
function createPromise(i) {
return new Promise(resolve =>
setTimeout(function () {
console.log(i);
resolve();
}, Math.random() * 1000)
)
}
test();
Here's the output of my code
9
1
7
8
0
6
3
2
5
4