我打电话一个Ajax请求中forEach
循环,但问题是,从阿贾克斯收到的响应时间,循环结束后(如果我没看错)如何使forEach循环中调用Ajax
foreach循环:
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);
}
});
});
函数调用是此行"profileData": getPhotos(entry.photo, req.token)
在上面的代码。
功能:
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调用:
function getApiResponse(url, params, next) {
unirest.get(url)
.query(params)
.timeout(60000)
.end(function (res) {
if (next)
next(res);
});
}
我能够打印的反应,但无法将其返回到调用函数。 "profileData"
的值为空字符串。我该如何处理?
什么是预期的返回值()'电话? getApiResponse是同步的吗? – guest271314
@ guest271314返回值是一个byteArray。我不认为'getApiResponse'是同步的。我没有同步,因为我读的地方不是很好的做法 – Satyadev
@Satyadev如果'entry.phoneNumber'是一个空字符串,预期的结果是什么?如果'getApiResponse'是异步的,那么你为什么要在'getPhotos'调用中立即返回base64Image'?你期望'retrieveContacts.profileData'值是什么? – guest271314