繁体   English   中英

节点。 js带有多个http请求的嵌套异步映射

[英]Node. js Nested async map with multiple http request

在这里,我尝试循环处理URLS数组,并从一组URL中获取响应并处理响应URL。 在代码中,我希望外部循环在完成所有内部请求之后进入,并希望结果如下所示。

在: https ://stackoverflow.com中检查Urls状态已完成.... .....在: https ://example.com ..... ..... ....中检查Urls

共有20条链接

但是在我的代码中,外部循环在请求完成之前就完成了。

const getHrefs = require('get-hrefs');
const async = require("async");
var req = require('request-promise');
var errors = require('request-promise/errors');

var pageUrls = ['https://stackoverflow.com','https://www.exsample.com'];
testUrls='';

async.map(pageUrls, function(pageUrl,callback){
    //process itemA
    req(pageUrl, function (err, response, body) {
        console.log(pageUrl, " STATUS: ", response.statusCode);
        if ( err){
            return callback(err);
        } 
        else {
        testUrls= getHrefs(response.body);

        async.map(testUrls, function(testUrl,callback1){
             linkCount++;
               req(testUrl).catch(errors.StatusCodeError, function (reason) {
                        brokenLinks++;
                        console.log("URL: "+ testUrl+ "reason: "+ reason.statusCode);
                    })
                    .catch(errors.RequestError, function (reason) {

                    }).finally(function () {


                    });

                return  callback1();
             },function(err){

                 callback();

              }) ;
        }
    })

} ,function(err){
    console.log("OuterLoopFinished");
    console.log('*************************************************************' + '\n');
    console.log('Check complete! || Total Links: ' + linkCount + ' || Broken Links: ' + brokenLinks);
    console.log('*************************************************************');

});

我认为您应该重新考虑您的方法。 这使400个URL。 您应该并行触发所有请求(用于子链接),然后可以从主机URL跟踪损坏的URI的计数。 这样可以更快地完成脚本。

const pageUrls = ['https://stackoverflow.com','https://www.google.com'];
const rp = require('request-promise');
const allRequestPromises = [];
const getHrefs = require('get-hrefs');

const checkBrokenCount = (url, host) => {
  rp(url).then((response) => {
    console.log('valid url', url, host);
    // other code
  })
  .catch((error) => {
    console.log('invalid url', url, host);
  });
}

pageUrls.forEach((pageUrl)=> {
  // Lets call all the base URLs in parallel asuming there are not incorrect.
  allRequestPromises.push(rp({uri: pageUrl, resolveWithFullResponse: true}));
});
Promise.all(allRequestPromises).then((responses) => {
  responses.forEach((response, index) => {
    // Promise.all guarantees the order of result.
    console.log(pageUrls[index], response.statusCode);
    const testUrls= getHrefs(response.body);
    testUrls.forEach((testUrl) => {
      checkBrokenCount(testUrl, pageUrls[index]);
    });
  });
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM