【发布时间】:2015-08-14 07:36:41
【问题描述】:
我一直在使用 node.js,我需要使用 jsons 检查数组并更新一些项目,最后返回更新后的数组。 我正在做的事情是这样的:(主应用程序使用 express 和 sequelize)
exports.getDetails = function (req, res) {
var accountsArray = [];
bluebird.map(req.accounts, function(account, callback){
if (account.type == 'A'){
if (account.param == req.body.paramSearch){
account.updateAttributes({
param: req.body.paramSearch
}).then(function(updatedAccount){
console.log('A type entry');
accountsArray.push(updatedAccount);
});
}
else{
console.log('A type entry');
accountsArray.push(account);
}
}
if (account.type == 'B'){
if (account.param == req.body.paramSearch){
account.updateAttributes({
param: req.body.paramSearch
}).then(function(updatedAccount){
console.log('B type entry');
accountsArray.push(updatedAccount);
});
}
else{
console.log('B type entry');
accountsArray.push(account);
}
}
}).then(function(){
console.log('Bluebird.map done');
res.status(200).json({
data: {
accounts: accountsArray
}
});
});
我打算做的是首先将所有帐户(更新的受害者与否)添加到 accountsArray,然后才返回带有 accountsArray 的 json。
相反,我得到的是一个空的 accountsArry。我在代码中使用了 console.logs 来跟踪事情的处理方式。我总是得到类似的东西
Bluebird.map done
A/B type entry
...
A/B type entry
预期是
A/B type entry
...
A/B type entry
Bluebird.map done
我是 node.js 的新手,这种异步处理仍然让我感到困惑。 有没有办法确保我已经完成了地图部分内的子功能,然后才继续响应?如果可能,使用 Bluebird。
非常感谢任何帮助。
【问题讨论】:
标签: javascript node.js asynchronous bluebird