我有一个非常奇怪的问题,我的 Promise 的 .then 不起作用。错误如下:
类型错误:无法读取未定义的属性“then”
我称之为奇怪的原因是因为我在其他地方使用相同的结构并且它完美无缺。我还想补充一点,它应该做的实际行动 - 确实完成了!所以这纯粹是我的 Promise 的“编码”方式的问题——只是语法糖。
我的代码片段如下:
var updateAllUnreadNotifications = function(){
userModel.aggregate([
{$match:{"profileID": 123}},
{$unwind: "$notifications"},
{$match:{"notifications.read": false}},
{$group: {_id:"$_id", notifications: {$push:"$notifications"}}}
], function(err, notifications){
var notificationPromises = notifications.map(function(notification) {
return new Promise(function(resolve){
userModel.findOneAndUpdate(
{profileID: 123, "notifications.id": notification.id},
{"notifications.$.read": true},
{safe: true},
function(err, result) {
if (err){
return;
} else if (result){
resolve(notification);
}
}
);
});
});
return Promise.all(notificationPromises);
});
};
updateAllUnreadNotifications()
.then(function(notifications){
res.json({
message: 'All is well'
});
});
此外,我在notificationPromises上做了一个console.log,它看起来确实像一个Promises 链。当然,结果变量也在那里,所以这不是 DB 命令的问题。
我搞砸了什么?我相信这将是一个非常明显的问题,但对于我的生活,我无法孤立它。
如果需要更多信息,请告诉我。
您需要promise
从updateAllUnreadNotifications
函数返回,但不会从该函数返回任何内容。这就是您收到该错误的原因。
我会说更好的方法是制作一个单独的函数来处理通知并像这样链接承诺
var updateAllUnreadNotifications = function(){
return new Promise(function(resolve,reject){
userModel.aggregate([
{$match:{"profileID": 123}},
{$unwind: "$notifications"},
{$match:{"notifications.read": false}},
{$group: {_id:"$_id", notifications: {$push:"$notifications"}}}
], function(err, notifications){
if(err){ reject(err)}
// If got notifications then resolve
// notifications will be available to next then function
resolve(notifications)
})
})
}
var processNotifications = function(notifications) {
var notificationPromises = notifications.map(function(notification) {
return new Promise(function(resolve){
userModel.findOneAndUpdate(
{profileID: 123, "notifications.id": notification.id},
{"notifications.$.read": true},
{safe: true},
function(err, result) {
if (err){
return;
} else if (result){
resolve(notification);
}
}
);
});
});
return Promise.all(notificationPromises);
};
// Chain one extra then here to process notifications
updateAllUnreadNotifications().then(processNotifications)
.then(function(notifications){
res.json({
message: 'All is well'
});
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句