A Little Misconception about Promise (nodeJS)

Consider the following code

var Promise = require('bluebird');

function f(x){
  return Promise.try(function(){
    console.log("start " + x);
    return Promise.delay(500);
  })
  .then(function(){
    console.log("finish " + x);
  });
}

var promises = [];
promises.push(f(1));
promises.push(f(2));

Promise.each(promises, function(){
  return f;
});

Expected result:

start 1
finish 1
start 2
finish 2

But when we run the code, the actual result is

start 1
start 2
finish 1
finish 2

So what part is wrong?
Until now I have a very wrong assumption that the function inside Promise.try() will be executed when it is called inside Promise.each. But it is actually called synchronously the moment f(x) function is invoked.

So the correct way to write the code is wrap the f(x) function call inside another function like the following.

var promises = [];
promises.push(function(){
  return f(1);
});
promises.push(function(){
  return f(2);
});

Promise.each(promises, function(p){
  return p();
});
Advertisements
This entry was posted in Programming and tagged , . Bookmark the permalink.

2 Responses to A Little Misconception about Promise (nodeJS)

  1. kalau di-run code yang terakhir hasilnya malah (node 6.10, bluebird 3.5.0):

    start undefined
    finish undefined
    start undefined
    finish undefined

    mungkin maksudnya gini kah?

    var promises = [1, 2];
    Promise.each(promises, function(x){
    return f(x);
    });

    oh dan btw console.log() nya typo tuh hehe

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s