我是 node.js 的新手,我必须解决其中的一个错误。我正在尝试通过以下服务更新组成员,每当我尝试调用此 API 时,都会出现错误
Error: Callback was already called.
我的代码是:
'app.post('/api/updateGroup/:group_id', function (req, res) {
var checkGroup = Group.findOne({'_id': req.params.group_id}).exec();
checkGroup.addBack(function( err , existingGroup ) {
if ( err ) {
res.json({'message' : err });
}else if( existingGroup ){
Group.findOne({ '_id': req.params.group_id })
.execQ()
.then(function(existingUser) {
var friendphoneNumber = req.body.friendphoneNumber.split(',');
var friends = [];
console.log('existingUser', friendphoneNumber);
async.each(friendphoneNumber, function(phonenum, callback) {
var phonenum = phonenum.split("\'")[0];
console.log('phonenum', phonenum);
User.findOne({
'phoneNumber': phonenum
})
.execQ()
.then(function(existingFriend) {
if(existingFriend === null) {
friends.push({
'details': {
'phoneNumber': phonenum
}
});
callback();
} else {
friends.push({'details': existingFriend});
callback();
}
})
.catch(function(err) {
console.log('err', err)
friends.push({
'details': {
'phoneNumber': phonenum
}
});
callback();
})
.done(function() {
});
}, function(err) {
console.log('callback')
group.group_id = req.params.group_id;
// group.user_id = req.body.userId;
// group.createdDate = moment().format('YYYY-MM-DD hh:mm a');
group.friends = friends;
group.update(function(err) {
if (err) {
res.json({
message: err
});
} else {
res.json({
success: 1,
message: 'Group updated',
group: group
});
}
});
});
})
.catch(function(err) {
res.json({
success: 0,
message: 'user id Not Match. Please try again'
});
})
.done(function(events) {
});
}
else {
console.log('nope');
}
});
});
关于同样的问题,我看到的答案很少,但我仍然无法解决。
最佳答案
如果 callback
抛出错误,它将在 then
和随后的 catch
中被调用。您可能应该在 done
函数中调用它。
.then(function(existingFriend) {
if(existingFriend === null) {
friends.push({
'details': {
'phoneNumber': phonenum
}
});
} else {
friends.push({'details': existingFriend});
}
})
.catch(function(err) {
console.log('err', err)
friends.push({
'details': {
'phoneNumber': phonenum
}
});
})
.done(function() {
callback();
});
关于javascript - 异步 Node JS : Error: Callback was already called,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30552376/