Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 628
Nissim Hania Avatar asked Feb 29 '16 21:02

Nissim Hania


1 Answers

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 }
like image 77
Bryan Chen Avatar answered Oct 27 '22 00:10

Bryan Chen