【发布时间】:2017-08-18 10:25:39
【问题描述】:
我正在尝试按顺序执行一些动态查询,但出于任何原因,下一个代码无法满足所需的行为。
var createEvent = function (user, notification) {
var action, query;
query = { agent: notification.agent, story: notification.story, type: notification.type };
action = { agent: notification.agent, story: notification.story, type: notification.type, ts: notification.ts };
return mongoose.model('Event').findOne(query).exec()
.then(function (response) {
if (response === null) {
return mongoose.model('Event').create(action)
.then(function (response) {
return mongoose.model('User').findByIdAndUpdate(user, { $push: { notifications: { _id: response._id }}});
});
}
return mongoose.model('User').findByIdAndUpdate(user, { $push: { notifications: { _id: notification._id }}}).exec();
});
setTimeout(resolve, 3000);
};
var moveNotifications = function (users) {
var promises = [];
users.map(function (user) {
if (user.notifications.length > 0) {
user.notifications.map(function (notification) {
promises.push(createEvent(user._id, notification));
});
}
});
Promise.each(promises, function (queue_item) {
return queue_item();
});
};
有人可以帮我吗?
【问题讨论】:
-
几件事......
setTimeout(resolve, 3000);永远不会被执行,因为它在return之后 - 但那也一样,resolve无论如何都没有定义。其次,您在 .map 回调中调用createEvent- 所以所有这些findOne调用在第一个 .then 调用之前都是“飞行中”
标签: javascript mongoose promise bluebird