Here I am trying to loop array of URLS and get the response from one set of URLs and process the response URLs . In code I want the outer loop should enter after completing all the inner request and want the result like below.
Checking Urls in : https://stackoverflow.com status 200 done .... .... Checking Urls in : https://example.com ..... ..... .....
Total links #20
But in my code outer loop is finishing before the request done.
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('*************************************************************');
});
callback1too early. Try putting it inside thefinallyblock.callback1marks the end of the innerasync.mapexecution (for eachtestUrlsitems). The completion ofasync.map(testUrls...callscallbackwhich marks the end of the outerasync.mapexecution (for eachpageUrlitems). The completion ofasync.map(pageUrl...calls theouterloopfinishedfunction...async.mapcallback function (thefunction(err){ "Outerloopfinished".. }and thefunction(err) { callback(); }) is called when all iteratee functions have finished, OR AN ERROR OCCURS (see: caolan.github.io/async/docs.html#map). It's possible that your firstIFbranch (if ( err){ return callback(err); }) invoked an early termination...