I am calling a ajax request inside forEach
loop but the problem is that by the time the response is received from ajax, the loop is finished(if I am not wrong)
forEach Loop:
var retrievedContacts = {};
var retrievedContactsArr = [];
contacts.getContacts(function (err, contacts) {
contacts.forEach(function (entry) {
if (entry.phoneNumber !== '') {
retrievedContacts = {
contact: {
"address": {
"home": "",
"office": ""
}
},
"profileData": getPhotos(entry.photo, req.token)
};
retrievedContactsArr.push(retrievedContacts);
}
});
});
Function call is this line "profileData": getPhotos(entry.photo, req.token)
in the above code.
Function:
function getPhotos(url, token){
var base64Image = '';
getApiResponse(url+"?access_token="+token,"", function (res1) {
if (res1.error) {
console.log('Could not fetch google photos......', res1.error);
} else {
base64Image = new Buffer.from(res1.body).toString('base64');
console.log('base64 is.........................', base64Image);
}
});
return base64Image;
}
Ajax call:
function getApiResponse(url, params, next) {
unirest.get(url)
.query(params)
.timeout(60000)
.end(function (res) {
if (next)
next(res);
});
}
I am able to print the response but unable to return it to the calling function. The value of "profileData"
is empty string. How do I handle this?