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
.then
needs a callback , not a Promise - at the moment, you're calling createPromise(i)
immediately , inside the loop. Create a function that, when called, returns a Promise instead:
p = p.then(() => createPromise(i));
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();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.