I want to return an array of names after a forEach inside an asynchronous method. Both the for each and the res.send are inside the Asyn. Method. The forEach works perfectly, but I always get an empty array.
This is my request in the website side:
function retrieveCharity(){
$.ajax({
type:"GET",
url: "http://xxx.xxx.x.xx:9000/charity",
success: function(data){
data.charities.forEach(function(charityName){
$(".charity-ul").append("<li>"+charityName+"</li>");
})
}
})
}
This is my router.get listener in the NodeJs side:
router.get('/', function (req, res){
log.d("Entrou no method post - Charity");
teamModel.find({},function(err,charities){
var charityMap = {};
if(err){
console.log("Err in retrieving Charity")
log.d("Err in retrieving")
res.send({
"status":"error"
})
}else{
charities.forEach(function(charity){
charityMap[charity._id]= charity.teamName;
console.log("Print here the name of the charities I have,PLEASE" + charity.teamName);
log.d("foEach - data",charity);
})
res.send({
"charities": charityMap
})
}
})//end of findCahrity
});
All the log.d and the information I ask to be printed inside them is correct, and they are printed. The problem is that the array I return is always empty, but both(forEach) and res.send are inside the asynchronous method.
I always get this in post man:
{
charities: { }
}
and the console always says :
Uncaught TypeError: undefined is not a function
this line :
data.charities.forEach(function(charityName){
Can someone help me please. What am I doing wrong?
Thanks in advance.
I don't think Object.prototype.forEach
is standard.
data.charities
is an object not an array. You could try to change your router code from
var charityMap = {};
with charityMap[charity._id]= charity.teamName;
to
var charityMap = [];
with charityMap.push(charity.teamName)
or change the iteration on the client side.