使用Bluebird实现Promises

时间:2015-06-10 13:19:52

标签: bluebird

我有一个需要用Bluebird Promises实现但无法解决的功能。这是一个伪代码

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!");

                }                   
        );

}

由于

1 个答案:

答案 0 :(得分:1)

这样的东西
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!");
});

您需要定义myError才能使其工作(https://github.com/petkaantonov/bluebird/blob/master/API.md#catchfunction-errorclassfunction-predicate-function-handler---promise

P.S。当然,req.db.Employee.create(item)应该支持promises,所以你可能需要宣传它:https://github.com/petkaantonov/bluebird/blob/master/API.md#promisepromisifyallobject-target--object-options---object