Nissim Hania
Nissim Hania

Reputation: 99

Promises in nodeJS / a callback within a promise / order of executions is not right

When I am chaining multiple promises and I expect that each promise will execute only after the previous one ended. Somehow it does not happen. I am sure using promises wrong and would love for some explanation.

I have this code:

var Promise     = require('bluebird');

func('A')
    .then(() => {func('B')})
    .then(() => {func('C')})
    .then(() => {func('D')})

function func(arg) {
    return new Promise(function(resolve){
        console.log('>> ' + arg);
        setTimeout(function(){
            console.log('  << ' + arg);
            resolve();
        }, 200)
    })
}

I was expecting to get this output:

>> A
  << A
>> B
  << B
>> C
  << C
>> D
  << D

But instead, I get this output:

>> A
  << A
>> B
>> C
>> D
  << B
  << C
  << D

What am I getting wrong?

Upvotes: 6

Views: 94

Answers (1)

Bryan Chen
Bryan Chen

Reputation: 46578

You need to return the promise

func('A')
    .then(() => {return func('B')})
    .then(() => {return func('C')})
    .then(() => {return func('D')})

or

func('A')
    .then(() => func('B'))
    .then(() => func('C'))
    .then(() => func('D'))

Ignoring Lexical this or Lexical arguments part,

() => {1} translate to

function() { 1 } // return undefined

and () => 1 translate to

function() { return 1 }

Upvotes: 9

Related Questions