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

垃圾劫匪

我有一个功能,需要抓取网站并返回地址列表。在从抓取中进行的回调中,对于返回的每个地址,我需要执行另一次抓取操作,然后处理数据,然后我想返回整个处理后的集合。如果需要的话,我不介意封锁。最终,我必须将整个集合作为一个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?
        }
    }); 
}
mscdex

这是使用异步模块的一种解决方案

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章