等待请求完成并返回数据

时间:2016-01-08 19:59:21

标签: javascript node.js asynchronous callback q

我正在使用节点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');
    });
  }
}

1 个答案:

答案 0 :(得分:0)

那里没有与q相关的代码,但是q.all收到了一系列承诺并在所有这些承诺得到解决时解决,所以你可以这样做...... < / p>

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
});