使用 Bluebird 实现 Promise

Implementing Promises using Bluebird

我有一个函数需要用 Bluebird Promises 实现,但无法解决。这是一个伪代码

exports.addEmployees=函数 (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!");

                }                   
        );

}

谢谢

类似

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) 应该支持承诺,所以您可能需要承诺它:https://github.com/petkaantonov/bluebird/blob/master/API.md#promisepromisifyallobject-target--object-options---object