0

I'm trying to understand the es6 Promises. As I understood, they can be chained to be executed sequentially. It does not work in by case.

console.log("Started");

function doStuff(num, timeout) {
    return new Promise(function(resolve, reject) {
        setTimeout(function() {
            console.log("now " + num);
            resolve();
        }, timeout);
    });
}

doStuff(1, 3000).then(doStuff(2, 2000)).then(doStuff(3, 1000));

However the output is:

$ node test
Started
now 3
now 2
now 1

I was expecting the reverse order. I do understand why it gets like this, they are all queued up and finishes in the "reverse" order.

But the thing is, I thought that the second was not executed until the first was finished and so on. What am I missing?

Pa Ye
  • 1,779
  • 12
  • 22
kaze
  • 4,299
  • 12
  • 53
  • 74

3 Answers3

3

If you write it like this, the 3 calls to doStuff will start when you write the line. You have to write it like this :

doStuff(1, 3000).then(function() {
    return doStuff(2, 2000);
}).then(function() {
    return doStuff(3, 3000);
});

As loganfsmyth said, is you are doing ES6, you can also use arrow functions :

doStuff(1, 3000).then(() => doStuff(2, 2000)).then(() => doStuff(3, 3000));
Magus
  • 14,796
  • 3
  • 36
  • 51
0

Isn't there a typo ? you should chain the then part to the doStuff call, perhaps like this:

doStuff(1, 3000).then(function(){
    doStuff(2, 2000).then(function(){
        doStuff(3, 1000);
    });
});
Roba
  • 646
  • 4
  • 13
0

timeouts in javascript are asynchronous. The way you have it written now, all three promises are executed in order, and the timeout function just queues up the code inside of it to run after a certain time duration. A timeout's execution doesn't mean its resolution; it's considered "done" when its internal code is queued. That's why the second and third promises don't have to wait for the line "console.log("now " + num);" to execute before being kicked off.

See this answer https://stackoverflow.com/a/19626821/2782404 for some background on asynchronous tasks in js.

Community
  • 1
  • 1
kwills
  • 116
  • 10