Implementing Promises using Bluebird

132 views Asked by At

I have a function which needs to be implemented with Bluebird Promises but unable to work it out. Here is a pseudo code

exports.addEmployees=function (req,res){

var data =  [
                {
                    firstName: 'XXXXX',
                    lastName: 'V',
                    phone: '9999999999',
                    dateOfBirth: '2010-08-02',
                    department: 'IT',
                    startDate: '2015-08-02',
                    created: now,
                    updated: now
                },
                {
                    firstName: 'YYYYY',
                    lastName: 'K',
                    phone: '8888888888',
                    dateOfBirth: '2011-08-02',
                    department: 'IT',
                    startDate: '2015-08-02',
                    created: now,
                    updated: now
                },
            ];



async.each(data, function(item,callback){

                    req.db.Employee.create(item, callback);         

                },function(err){

                    if(err){

                        res.send("Error!");

                    }
                    res.send("Success!");

                }                   
        );

}

Thanks

1

There are 1 answers

1
Michael Plakhov On BEST ANSWER

Something like

var Promise = require("bluebird")

var data =  [
                {
                    firstName: 'XXXXX',
                    lastName: 'V',
                    phone: '9999999999',
                    dateOfBirth: '2010-08-02',
                    department: 'IT',
                    startDate: '2015-08-02',
                    created: now,
                    updated: now
                },
                {
                    firstName: 'YYYYY',
                    lastName: 'K',
                    phone: '8888888888',
                    dateOfBirth: '2011-08-02',
                    department: 'IT',
                    startDate: '2015-08-02',
                    created: now,
                    updated: now
                },
            ];


Promise.map(data, function(item) {
    return req.db.Employee.create(item)
        .then(function(id){ return id })
        .catch(MyError, function(e) {
            e.item = item;
            throw e;
        })
}).then(function(idList) {
    res.send("Success!");
}).catch(MyError, function(e) {
    console.log("Operation failed on " + e.item + ": " + e.message);
    res.send("Error!");
});

You need to define myError to make this work (https://github.com/petkaantonov/bluebird/blob/master/API.md#catchfunction-errorclassfunction-predicate-function-handler---promise)

P.S. Sure, req.db.Employee.create(item) should support promises, so probably you will need to promisify it: https://github.com/petkaantonov/bluebird/blob/master/API.md#promisepromisifyallobject-target--object-options---object