如何使节点js等待函数执行(即使需要时间)然后执行下一个语句

时间:2016-07-21 12:16:15

标签: javascript xml node.js function hapijs

如何使节点js等待函数执行(即使需要时间)然后执行下一个语句。对我来说问题是for循环打印所有url首先它不会等待require请求函数来检查每个URL的http响应。它只打印所有网址。因为我得到了错误

console.log(dd[i]['loc'][0]); 
                 ^

TypeError:无法读取未定义的属性“loc”

我的完整源代码如下

       var hapi = require('hapi');
    var glue = require('glue');
    var joi = require('joi');
    var handlebars = require('handlebars');
    var strop = require('string');
    var inert = require('inert');
    var async = require('async');
    var poop = require('poop');
    var bell = require('bell');
    var nconf = require('nconf');

    //xml parser starts

    var fs = require('fs'),
        xml2js = require('xml2js');

    var parser = new xml2js.Parser();
    fs.readFile('sitemapscene1.xml', function(err, data) {
    var count = 0;
    var a=0;
    var b=0;
    var c=0;
    var d=0;
    var e=0;
    var f=0;
    var g=0;
    var h=0;
    //parsing inside url starts
    var parseString = require('xml2js').parseString;

        parser.parseString(data, function (err, result) {
            ff = result;
            dd = ff['urlset']['url'];

            for (i =0; i< dd.length; i++){
             console.log(dd[i]['loc'][0]);
    //server reuest and checking
    var request = require('request');
    request(dd[i]['loc'][0], function (error, response, body) {
      if (!error && response.statusCode == 200) {
        console.log(dd[i]['loc'][0]); 
        console.log("This url http response is 200");
        count=count+1;
        console.log(count);
      }
    })



    }
    console.log("Total number of urls in this sitemap");
            console.log(dd.length);
            });

        });


    //xml parser ends

My full error code is 

    Total number of urls in this sitemap
22569

    console.log(dd[i]['loc'][0]); 
                     ^

TypeError: Cannot read property 'loc' of undefined
    at Request._callback 
    at Request.self.callback
    at emitTwo (events.js:87:13)
    at Request.emit (events.js:172:7)
    at Request.<anonymous> 
    at emitOne (events.js:77:13)
    at Request.emit (events.js:169:7)
    at IncomingMessage.<anonymous> 
    at emitNone (events.js:72:20)
    at IncomingMessage.emit (events.js:166:7)

我的实际完整代码

 var hapi = require('hapi');
var glue = require('glue');
var joi = require('joi');
var handlebars = require('handlebars');
var strop = require('string');
var inert = require('inert');
var async = require('async');
var poop = require('poop');
var bell = require('bell');
var nconf = require('nconf');
var async = require('async');

//xml parser starts

var fs = require('fs'),
    xml2js = require('xml2js');

var parser = new xml2js.Parser();
fs.readFile('sitemapscene1.xml', function(err, data) {
var count = 0;
var a=0;
var b=0;
var c=0;
var d=0;
var e=0;
var f=0;
var g=0;
var h=0;
//parsing inside url starts
var parseString = require('xml2js').parseString;

    parser.parseString(data, function (err, result) {
        ff = result;
        dd = ff['urlset']['url'];
        console.log("Total number of urls in this sitemap");
        console.log(dd.length);
        for (i =0; i< dd.length; i++){
         console.log(dd[i]['loc'][0]);

//sending to server to get response
var request = require("request");

request(dd[i]['loc'][0], function(error, response, body) {
    //console.log(response.statuscode);
if (!error && response.statusCode == 200) {

    count=count+1;

   console.log("Number of pages with responese.statuscode 200 is");
    console.log(count); 

    var ddddd = "Number of pages with responese.statuscode 200 is " + count + " " + dd[i]['loc'][0]
// output is wriiten in output.txt file start here

fs = require('fs');
fs.writeFile('output.txt', ddddd, function (err) {
  if (err) return console.log(err);
  console.log('Hello World > output.txt');
});

// output is wriiten in output.txt file ends here

    } else if ( error && response.statusCode == 400 ) {

         a=a+1;
    console.log("Number of pages with responese.statuscode 400 is");
    console.log(a);
    var ddddd = "Number of pages with responese.statuscode 200 is " + count + " " + dd[i]['loc'][0]
// output is wriiten in output.txt file start here

fs = require('fs');
fs.writeFile('output.txt', ddddd, function (err) {
  if (err) return console.log(err);
  console.log('Hello World > output.txt');
});

// output is wriiten in output.txt file ends here

    }else if ( error && response.statusCode == 402 ) {

         b=b+1;
    console.log("Number of pages with responese.statuscode 402 is");
    console.log(b);
    var ddddd = "Number of pages with responese.statuscode 200 is " + count + " " + dd[i]['loc'][0]
// output is wriiten in output.txt file start here

fs = require('fs');
fs.writeFile('output.txt', ddddd, function (err) {
  if (err) return console.log(err);
  console.log('Hello World > output.txt');
});

// output is wriiten in output.txt file ends here

    }else if ( error && response.statusCode == 403 ) {

         c=c+1;
    console.log("Number of pages with responese.statuscode 403 is");
    console.log(c);
    var ddddd = "Number of pages with responese.statuscode 200 is " + count + " " + dd[i]['loc'][0]
// output is wriiten in output.txt file start here

fs = require('fs');
fs.writeFile('output.txt', ddddd, function (err) {
  if (err) return console.log(err);
  console.log('Hello World > output.txt');
});

// output is wriiten in output.txt file ends here

    }else if ( error && response.statusCode == 404 ) {

         d=d+1;
    console.log("Number of pages with responese.statuscode 404 is");
    console.log(d);

    }else if ( error && response.statusCode == 500 ) {

         e=e+1;
    console.log("Number of pages with responese.statuscode 500 is");
    console.log(e);
    var ddddd = "Number of pages with responese.statuscode 200 is " + count + " " + dd[i]['loc'][0]
// output is wriiten in output.txt file start here

fs = require('fs');
fs.writeFile('output.txt', ddddd, function (err) {
  if (err) return console.log(err);
  console.log('Hello World > output.txt');
});

// output is wriiten in output.txt file ends here

    }else if ( error && response.statusCode == 502 ) {

         f=f+1;
    console.log("Number of pages with responese.statuscode 502 is");
    console.log(f);
    var ddddd = "Number of pages with responese.statuscode 200 is " + count + " " + dd[i]['loc'][0]
// output is wriiten in output.txt file start here

fs = require('fs');
fs.writeFile('output.txt', ddddd, function (err) {
  if (err) return console.log(err);
  console.log('Hello World > output.txt');
});

// output is wriiten in output.txt file ends here

    }else if ( error && response.statusCode == 504 ) {

         g=g+1;
    console.log("Number of pages with responese.statuscode 504 is");
    console.log(g);
    var ddddd = "Number of pages with responese.statuscode 200 is " + count + " " + dd[i]['loc'][0]
// output is wriiten in output.txt file start here

fs = require('fs');
fs.writeFile('output.txt', ddddd, function (err) {
  if (err) return console.log(err);
  console.log('Hello World > output.txt');
});

// output is wriiten in output.txt file ends here

    } else   {

         h=h+1;
    console.log("Number of pages with error is");
    console.log(h);
    var ddddd = "Number of pages with responese.statuscode 200 is " + count + " " + dd[i]['loc'][0]
// output is wriiten in output.txt file start here

fs = require('fs');
fs.writeFile('output.txt', ddddd, function (err) {
  if (err) return console.log(err);
  console.log('Hello World > output.txt');
});

// output is wriiten in output.txt file ends here

    }



});

        }
        //console.log("Number of urls,in this site map");
        //console.log(dd.length); //number of urls
    });
});

//xml parser ends

这是使服务器崩溃的代码,我认为我在代码中犯了错误,而不是服务器耗尽内存

    var hapi = require('hapi');
var glue = require('glue');
var joi = require('joi');
var handlebars = require('handlebars');
var strop = require('string');
var inert = require('inert');
var async = require('async');
var poop = require('poop');
var bell = require('bell');
var nconf = require('nconf');
var async = require('async');

//xml parser starts

var fs = require('fs'),
    xml2js = require('xml2js');

var parser = new xml2js.Parser();
fs.readFile('sitemapscene1.xml', function(err, data) {
var count = 0;
var a=0;
var b=0;
var c=0;
var d=0;
var e=0;
var f=0;
var g=0;
var h=0;
//parsing inside url starts
var parseString = require('xml2js').parseString;

    parser.parseString(data, function (err, result) {
        ff = result;
        dd = ff['urlset']['url'];

        for (i =0; i< dd.length; i++){
         console.log(dd[i]['loc'][0]);
//server reuest and checking
var asyncRequests = [];
var request = require('request');

dd.forEach(function(ddElement){
    asyncRequests.push(function(callback){
        request(ddElement.loc[0], function(error, response, body) {
            if (!error && response.statusCode == 200) {
                return callback(null, 1);
            }

        callback();
        });
    });
});

async.parallel(asyncRequests, function afterStatement(err, results){
    var count = 0;

    for (var i = 0; i < results.length; i ++){
                if (results[i]){
            count += results[i];
        }
    }
});



}
console.log("Total number of urls in this sitemap");
        console.log(dd.length);
        });

    });


//xml parser ends

1 个答案:

答案 0 :(得分:1)

您需要异步,那么为什么不使用它呢?

var asyncRequests = [];
var request = require('request');

dd.forEach(function(ddElement){
    asyncRequests.push(function(callback){
        request(ddElement.loc[0], function(error, response, body) {
            if (!error && response.statusCode == 200) {
                return callback(null, 1);
            }

        callback();
        });
    });
});

async.parallel(asyncRequests, function afterStatement(err, results){
    var count = 0;

    for (var i = 0; i < results.length; i ++){
        // I don't remember if something is send with callback(), so check data
        if (results[i]){
            count += results[i];
        }
    }
});

请下次发送可读和缩进的代码

编辑:如果你想计算得到一个与路线相关的结果的对象(我认为ddElement.loc [0]是路线):

var asyncRequests = [];
var request = require('request');

dd.forEach(function(ddElement){
    asyncRequests.push(function(callback){
        request(ddElement.loc[0], function(error, response, body) {
            callback(error, {
                statusCode : response.statusCode,
                route : ddElement.loc[0]
            });
        });
    });
});

async.parallel(asyncRequests, function afterStatement(err, results){
    if (err){
        console.error(err);
    }

    console.log(results);
});