Bluebird promises - each function

Jay picture Jay · Jul 31, 2015 · Viewed 14.1k times · Source

Thank in advance for the help.

While using Bluebird promises, I have a series of promises running. During the last promise, I want to run one function multiple times for each object in an array.

Below there is the pseudocode:

var userArray = [ 
    {
        name: "John",
        email: "[email protected]"

    },
    {
        name: "Jane",
        email: "[email protected]"
    }]; 

var functionOne = function() {
    //returns Promsie object
};

var functionTwo = function() {
    //returns promise object
};

var createUser = function(user) {
    return User.findOrCreate({email: user.email},{
        name: user.name,
        email: user.email
    });
};

functionOne()
    .then(functionTwo)
    .each(createUser(userArray))
    .then(function onComplete() {
        console.log("Complete");
    })
    .catch(function onError() {
        console.log("Um...it's not working");
    });

I know I'm not using the each function correctly. What's the correct way to implement this using Bluebird?

Answer

Roman Sachenko picture Roman Sachenko · Jul 31, 2015

As I understand you want to take some asynchronous actions for elements from array. Then please check the following example:

var Promise = require('bluebird');

function createUsersFromArray(userArray){
    return Promise.each(userArray, function(signleUser){
        return createUserFunction(signleUser);
    });
}

or

return Promise.each(userArray, createUserFunction);

functionOne()
  .then(functionTwo)
  .then(function(){
      return createUsersFromArray(userArray);
  })
//or just .then(createUsersFromArray) if functionTwo return this array
  .then(function(createdUsers){
      //here you may retrieve users and make some magic with them
      console.log(createdUsers);
  })
  .then(function onComplete() {
      console.log("Complete");
  })
  .catch(function onError() {
      console.log("Um...it's not working");
  });

I also recommend using "all" instead of "each"

Check the examples below:

return Promise.all(userArray.map(function(singleUser){
    return doSomethingWithUser(singleUser);
}));

or

return Promise.all(userArray.map(doSomethingWithUser));

'all' will notify you if all the actions are taken correctly.

How to use promises (best practice):

http://pouchdb.com/2015/05/18/we-have-a-problem-with-promises.html https://blog.domenic.me/youre-missing-the-point-of-promises/