等待所有回调完成后再返回对象

Wait for all callback to complete before returning objects

本文关键字:返回 对象 回调 等待      更新时间:2023-09-26

我有一个函数需要抓取一个网站并返回地址列表。在scrape的回调中,对于返回的每个地址,我需要做另一个scrape操作,然后处理数据,然后我想返回整个处理后的集合。如果必须的话,我不介意阻塞。最终,我必须得到一个包含整个集合的JSON对象。这可能吗?我该怎么做?

function doSomething(req, res){
    var collection = [];
    scrape1(params, function(error, addresses){
        if(!error){
            for(var i in addresses){   
                //do some stuff with addresses here
                scrape2(otherparams, function(error, address, data){
                    //manipulate the data here
                    collection.push({ 'address' : address, 'data' : data})  
                });
            }
            //this just returns an empty set obviously
            res.json(collection);
            //how can I return the entire collection from this function?
        }
    }); 
}

这里有一个使用异步模块的解决方案:

function doSomething(req, res){
  var collection = [];
  scrape1(params, function(error, addresses){
    if (error)
      return console.error(err); // handle error better
    async.each(addresses, function(address, callback) {
      scrape2(otherparams, function(err, address, data){
        // manipulate the data here
        if (err)
          return callback(err);
        collection.push({ 'address' : address, 'data' : data});
        callback();
      });
    }, function(err) {
      if (err)
        return console.error(err);  // handle error better
      res.json(collection);
    });
  }); 
}