1

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
Ewan
  • 79
  • 4

1 Answers1

2

.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();
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320