【发布时间】:2014-09-27 15:12:03
【问题描述】:
对 Promisification 不熟悉,不太确定 .then 和 .each 是否在整个 Promise 中携带变量。
另外,我在第四行明确定义了docReplies,但控制台日志:
可能未处理的 ReferenceError: docReplies 未定义
我希望循环遍历 repliesIDsArray 中的每个元素(replyID)并 findOneAsync 消息..然后为 doc.replies 数组中的每个元素找到 replyID 的索引,将其设置为 index1..then 对于每个doc.replies[index1] 数组中的元素找到用户名的索引(res.locals.username),将其设置为 index2..然后使用 index1 和 index2,保存字段以保存到文档..
(Here's a link to where this derives, with an outline of the db schema if that helps)
Promise.each(repliesIDsArray, function(replyID){
Models.Message.findOneAsync({'_id': req.params.message_id})
.then(function(doc){
var docReplies = [];
pushReplies = docReplies.push(doc.replies);
}).each(docReplies, function (replyIndex){
// loop over doc.replies to find..
// ..the index(index1) of replyID at replies[index]._id
var index1;
if (docReplies[replyIndex]._id == replyID) {
index1 = replyIndex;
}
var docRepliesIndex1 = [];
pushRepliesIndex1 = docRepliesIndex1.push(doc.replies[index1]);
}).each(docRepliesIndex1, function (usernameIndex){
// loop over doc.replies[index1].to and find..
// ..the index(index2) of res.locals.username at replies[index1].to[index2]
var index2;
if (docRepliesIndex1.to[usernameIndex].username === res.locals.username) {
index2 = usernameIndex;
}
}).then(function(index1, index2) {
console.log('index1 = ' + index1);
console.log('index2 = ' + index2);
doc.replies[index1].to[index2].read.marked = true;
doc.replies[index1].to[index2].read.datetime = req.body.datetimeRead;
doc.replies[index1].to[index2].updated= req.body.datetimeRead;
doc.markModified('replies');
var saveFunc = Promise.promisify(doc.save, doc);
return saveFunc();
console.log('doc saved');
}).then(function(saved) {
console.log("Success! doc saved!");
console.log("Sending saved doc:");
res.json(saved);
}).catch(Promise.OperationalError, function(e){
// handle error in Mongoose findOne + save
console.error("unable to save because: ", e.message);
console.log(e);
res.send(e);
throw err;
}).catch(function(err){
// would be a 500 error, an OperationalError is probably a 4XX
console.log(err);
res.send(err);
throw err; // this optionally marks the chain as yet to be handled
});
})
【问题讨论】:
标签: node.js mongodb promise node-mongodb-native bluebird