Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
80
rated 0 times [  84] [ 4]  / answers: 1 / hits: 32443  / 10 Years ago, wed, december 17, 2014, 12:00:00

Hi I am trying to use the Async module to retrieve two users and do some processing after they have both been retrieved however I keep getting the error message: Callback was already called. Below is the code i currently have:



app.get('/api/addfriend/:id/:email', function(req, res) {
var id = req.params.id;
var friendEmail = req.params.email;
async.parallel([
//get account
function(callback) {
accountsDB.find({
'_id': ObjectId(id)
}, function(err, account) {
console.log(id);
if (err || account.length === 0) {
callback(err);
}
console.log(account[0]);
callback(null, account[0]);
});
},
//get friend
function(callback) {
accountsDB.find({
'email': friendEmail
}, function(err, friend) {
console.log(friendEmail);
if (err || friend.length === 0 || friend[0].resId === undefined) {
callback(err);
}
console.log(friend[0]);
callback(null, friend[0].resId);
});
}
],

//Compute all results
function(err, results) {
if (err) {
console.log(err);
return res.send(400);
}

if (results === null || results[0] === null || results[1] === null) {
return res.send(400);
}

//results contains [sheets, Friends, Expenses]
var account = results[0];
var friend = results[1];
if (account.friends_list !== undefined) {
account.friends_list = account.friends_list + ',' + friend;
}
else {
account.friends_list = friend;
}
// sheetData.friends = results[1];
accountsDB.save(
account,
function(err, saved) {
if (err || !saved) {
console.log(Record not saved);
}
else {
console.log(Record saved);
return res.send(200, friend added);
}
}
);

}
);
});


Any help would be appreciated.


More From » node.js

 Answers
30

Add else statement to your code, because if you get error, your callback executes twice



if (err || account.length === 0) {
callback(err);
} else {
callback(null, account[0]);
}

[#68464] Saturday, December 13, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
minab

Total Points: 701
Total Questions: 104
Total Answers: 91

Location: Saint Pierre and Miquelon
Member since Fri, Jan 28, 2022
2 Years ago
;