我在互联网上对此问题做了很多研究,但仍然无法知道问题的原因。
问题是,当我使用异步库中的并行函数时,出现错误:
Callback was already called.
这是我的代码:(我已经对出现此错误的行进行了评论)
var sendNotificationAddToMyRememberNew = function(request, response, restaurant) {
async.parallel({
notification_list: function (callback) {
models.NotificationList.create({
alert_msg: "Restaurant " + restaurant.name + " remembered.",
payload: JSON.stringify({
restaurant_id: restaurant.id,
restaurant_name: restaurant.name,
restaurant_image: restaurant.image
}),
type: constants.NOTIFICATION_TYPE.RESTAURANT_REMEMBERED,
platform_type: constants.MOBILE_PLATFORM_TYPE.ALL,
status: constants.NOTIFICATION_STATUS.SENT,
device_token: null,
device_arn: null,
schedule_time: moment.utc(),
customer_id: request.token.customer_id,
customer_email: request.token.email,
created_date: moment.utc(),
updated_date: moment.utc()
}).then(function(notificationList){
callback(null, notificationList);
}).catch(function(error){
callback(error);
});
},
badge_count: function(callback) {
models.CustomerBadgeCount.findOrCreate({
where: {
customer_id: request.token.customer_id
},
defaults: {
badge_count: 1,
customer_id: request.token.customer_id,
created_date: moment.utc(),
updated_date: moment.utc()
}
}).spread(function (badgeCount, created) {
if(!created){
badgeCount.update(
{
badge_count: badgeCount.badge_count + 1,
updated_date: moment.utc()
},
{
fields:[
"badge_count",
"updated_date"
]
}
).then(function(badgeCount) {
callback(null, badgeCount);
}).catch(function (error) {
callback(error); // Getting error of callback here
});
}else{
callback(null, badgeCount)
}
}).catch(function (error) {
callback(error);
});
},
devices: function(callback) {
models.CustomerDeviceTokens.findAll({
where: {
customer_email: request.token.email
}
}).then(function(devices) {
callback(null, devices);
}).catch(function(error) {
callback(error);
});
}
}, function(error, results){
if(error) {
Logger.logDbError(error,request);
return console.log(error);
}
//callback function
console.log("-------------------------------------------------------");
console.log("Notification List: " + JSON.stringify(results.notification_list, null, 4));
console.log("badge_count: " + JSON.stringify(results.badge_count, null, 4));
if(results.devices && result.devices.count > 0) {
results.devices.forEach(function(device) {
console.log("device_arn: " + device.device_arn);
}, this);
}
});
}
最佳答案
如果callback(null, badgeCount)
,就会发生这种情况抛出错误(如果最终回调由于某种原因抛出错误,则可能会发生这种情况)。
在这种情况下会发生的是 .catch
调用处理程序,在其中调用 callback
再次,导致“已调用”消息。
为了防止这种情况(或者更确切地说,捕获这些错误),您不应使用 .catch
但使用 .then
的两个参数版本:
.then(function(badgeCount) {
callback(null, badgeCount);
}, function (error) {
callback(error);
});
(与代码中在 .then().catch()
操作中使用 async
的所有其他位置类似)
关于javascript - 回调已经被调用。但在此之前我从未调用过回调。 async.parallel 中的错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45052884/