【发布时间】:2017-12-16 14:21:56
【问题描述】:
我在网上对这个问题做了很多研究,仍然无法知道问题的原因。
问题是,当我使用异步库中的并行函数时,出现错误:
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);
}
});
}
【问题讨论】:
-
不要将 async.js 与 Promise 一起使用。普通的
Promise.all要容易得多。 -
@Bergi 这个问题不重复。我已经解决了这个问题。请看我的回答。
-
副本解释了difference between
.then(…, …)and.then(…).catch(…),这是导致callback被调用两次的原因。 -
如果你觉得这个问题是重复的,那么请删除它。因为我不能删除它,因为这个问题已经有了答案。
-
@Bergi 对不起,我忘了在上面的评论中提到你的名字。请阅读。
标签: javascript node.js async.js