我正在使用 Node js 构建 Restful API,这是我的代码
有3个主要部分,我创建了一个必须返回一些数据的get方法
get 调用 getImportIoData,该方法有一个对外部 API 的请求,并且此方法调用另一个名为 getEmailFromWebSite 的方法,此另一个方法调用另一个请求, 如何等待每个请求完成返回数据
我知道这已在其他问题中得到回答,但我尝试了其中一些但没有成功
我尝试了 Async 和 q 库,这部分的回调也不起作用
if (item.website !== undefined){ getEmailFromWebSite(item.website, function(email){console.log(email); item.email = email;}); }
我不知道我是否做错了什么,
有人可以帮我解决这个问题吗?使用我的代码
提前致谢
router.get('/', function(req, res) {
var Type = req.query.Type;
var Locations = req.query.Locations;
var Page = req.query.Page;
res.send(getImportIoData(res, Type, Locations, Page));
});
function getImportIoData(res, Type, Locations, Page) {
var criteria = {
'search_terms': Type,
'geo_location_terms': Locations,
'page': Page
}
var url = consts.import_io + consts.import_key + consts.query +
encodeURIComponent(consts.api_url) + encodeQueryData(criteria) +
/*"&_user=" + consts.user + */"&_apikey=" + consts.api_key;
request(url, function(error, response, json) {
var data = JSON.parse(json);
if (!error && response.statusCode === 200) {
var doctors = _.forEach(data.results, function(item) {
if (item.website !== undefined){
getEmailFromWebSite(item.website, function(email){console.log(email); item.email = email;});
}
});
return data.results
}
//else
});
}
function getEmailFromWebSite(website, callback) {
var EmptyReturn='';
searchTerm = extractDomain(website).replace('www.', '');
if (searchTerm != ''){
var EH_APIURL = 'https://api.emailhunter.co/v1/search?domain='+searchTerm+'&api_key='+ consts.EmailHunterAPIKey;
request(EH_APIURL, function(error, response, json) {
var data = JSON.parse(json);
if (!error && response.statusCode === 200) {
if((data.emails).length != 0){
var Emailobject = data.emails;
var EmailString = returnEmails(Emailobject);
callback(EmailString);
}else
callback(EmptyReturn);
}else if (response.statusCode === 429)
console.log('The number of Request has been Reached for this account');
else if (response.statusCode > 500)
console.log('Error with Email Hunter Servers');
else
console.log('An Error Ocurred');
});
}
}
最佳答案
其中没有与 q
相关的代码,但 q.all
接收一组 promise 并在所有这些 promise 都得到解决时解析,因此您可以执行类似的操作..
var promises = [ promiseOne(), promiseTwo(), promiseThree() ];
q.all(promises).then(function(results) {
//results is an array with the resolution values from all your promises in the order you specified in the promises array
});
关于javascript - 等待请求完成并返回数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34685110/