Node.js 从For循环返回多个承诺

Node.js 从For循环返回多个承诺,node.js,promise,Node.js,Promise,我正在使用Express和Request创建一个scraper。 URL数组被传递给请求,然后请求通过for循环进行迭代。解析所有数据并解析所有数据后,回调调用res.send 我试图将其转化为承诺,但我相信我使用的for循环将不允许我这样做。如果循环导致了问题,是否有其他方法可以对其进行编码并获得相同的结果 回调方法 function scrape(callback){ for(var i = 0; i < urls.length; i++){

我正在使用Express和Request创建一个scraper。 URL数组被传递给请求,然后请求通过for循环进行迭代。解析所有数据并解析所有数据后,回调调用res.send

我试图将其转化为承诺,但我相信我使用的for循环将不允许我这样做。如果循环导致了问题,是否有其他方法可以对其进行编码并获得相同的结果

回调方法

    function scrape(callback){
        for(var i = 0; i < urls.length; i++){
            request(urls[i], function(error, response, html){
                if(!error && response.statusCode == 200){
                    // LOAD Cherio (jQuery) on the webpage
                    var $ = cheerio.load(html);
                    try{
                        var name = $(".name").text();
                        var mpn = $(".specs.block").contents().get(6).nodeValue.trim();
                        var jsontemp = {"MPN": "", "Name": "", "PriceList": {}};

                        jsontemp.MPN = mpn;
                        jsontemp.Name = name;
                        // Traverse the DOM to get tr tags and extract info

                        $(".wide-table tbody tr").each(function (i, row) {
                            var $row = $(row),
                                merchant = $row. attr("class").trim(),
                                total = $row.children(".total").text();
                                jsontemp.PriceList[merchant] = merchant;
                                jsontemp.PriceList[merchant] = total;
                        });
                    }
                    catch(err){
                        console.log('Error occured during data scraping:');
                    }

                        list.push(jsontemp);
                }
                else{
                    console.log(error);
                }
            count++;
            callback();
            });
        }
    }
});

scrape(() => {
    console.log(count);
    if(count == urls.length){res.send(list)}
});
函数刮取(回调){
对于(var i=0;i{
控制台日志(计数);
如果(count==url.length){res.send(list)}
});
承诺实施尝试

var urls = [
    "http://test.com/",
    "http://test.com/2"
];
var list = [];
var count = 0;

scrape().then((data) => {
            list.push(data)
            if(count == urls.length){res.send(list)}
        })
        .catch(error => console.log(error))


function scrape(){
    for(var i = 0; i < urls.length; i++){
        return new Promise(function (resolve, reject) {

            request(urls[i], function(error, response, html){

            if(!error && response.statusCode == 200){
                var $ = cheerio.load(html);
                try{
                    var name        = $(".name").text();
                    var mpn         = $(".specs.block").contents().get(6).nodeValue.trim();
                    var jsontemp    = {"MPN": "", "Name": "", "PriceList": {}};

                    jsontemp.MPN    = mpn;
                    jsontemp.Name   = name;

                    // TRAVERSING DOM FOR DATA //
                    $(".wide-table tbody tr").each(function (i, row) {
                        var $row = $(row),
                            merchant = $row. attr("class").trim(),
                            total = $row.children(".total").text();
                            jsontemp.PriceList[merchant] = merchant;
                            jsontemp.PriceList[merchant] = total;
                    });
                }
                catch(err){
                    console.log('Error occured during data scraping:');
                }

                    resolve(jsontemp);
            }
            else{
                console.log(error);
                return reject(error);
            }
        count++;
        });
    }
}
var url=[
"http://test.com/",
"http://test.com/2"
];
var列表=[];
var计数=0;
刮取()。然后((数据)=>{
列表.推送(数据)
如果(count==url.length){res.send(list)}
})
.catch(错误=>console.log(错误))
函数scrape(){
对于(var i=0;i
您需要将这些承诺存储在一个列表中,然后调用
Promise.all
以获取所有承诺:

function scrape() {
  var promises = []; // array of promises
  for(var i = 0; i < urls.length; i++) {
    var url = urls[i];
    var promise = new Promise(function(resolve, reject) {
      // ...
    };

    // add to array
    promises.push(promise);
  }

  // return a single promise with an array of the results
  // by using Promise.all
  return Promise.all(promises);
}
函数刮取(){
var promissions=[];//承诺数组
对于(var i=0;i

另外,不要使用循环变量(如
i
)使用
var
时,在循环内部的函数中
。相反,您应该在promise回调函数外部声明一个
url
变量,或者将
var
替换为较新的
let

您需要将这些承诺存储在一个列表中,然后调用
promise.all
,以便为每个事情:

function scrape() {
  var promises = []; // array of promises
  for(var i = 0; i < urls.length; i++) {
    var url = urls[i];
    var promise = new Promise(function(resolve, reject) {
      // ...
    };

    // add to array
    promises.push(promise);
  }

  // return a single promise with an array of the results
  // by using Promise.all
  return Promise.all(promises);
}
函数刮取(){
var promissions=[];//承诺数组
对于(var i=0;i
另外,在使用
var
时,不要在循环内的函数内使用循环变量(如
i
),而是应该在promise回调函数外声明
url
变量,或者用较新的
let
替换
var