简体   繁体   中英

Node.js Async Callback explain

I have a node.js file call test.js below. Don't know why the 'All done!' will always print out on the top of output. Can someone explain why the 'All done!' always be the first output in console. How can I print it as last line after all requests finished and exit the application? I tried to use setTimeout to make the 'All done' be the last, but it won't help since you never know how long each request will complete. Should I use process.exit()?

var async = require('async');
var request = require('request');
var http = require('http');

var websites = [
    'qz.com',
    'www.stackoverflow.com',
    'www.google.com'
];

//get header of each URL
var getHeader = function(url, callback){
  var options = {
    method: 'HEAD',
    host: url, 
    port: 80,
    timeout: 10000,
    followRedirect: true,
    maxRedirects: 10, 
    path: '/'
  };

  var req = http.request(options, function(res) {
    //If connect server successfully, get Status code and header
    console.log('website name:' + url);
    console.log('Status Code:' + res.statusCode);
    console.log(JSON.stringify(res.headers));
    console.log("\n");
  });

  //if Error happens print out error
  req.on('error', function(err) {
      console.log('website name:' + url);
    console.log(err);
    console.log("\n");
  });

  req.end();
  return callback(null);
}


async.each(websites, getHeader, function(err){
  // if error happens, remind user
    if(err) {
    console.log('one url failed to be processed.');
  } else {
    console.log('All done!');  //print all done when all request complete
  }

});

You're calling the callback immediately at the end of your getHeader function. You need to instead call it when the request completes:

var getHeader = function(url, callback){
  var options = {
    method: 'HEAD',
    host: url, 
    port: 80,
    timeout: 10000,
    followRedirect: true,
    maxRedirects: 10, 
    path: '/'
  };

  var req = http.request(options, function(res) {
    //If connect server successfully, get Status code and header
    console.log('website name:' + url);
    console.log('Status Code:' + res.statusCode);
    console.log(JSON.stringify(res.headers));
    console.log("\n");
    res.resume(); // flush response stream just in case
    callback();
  });

  //if Error happens print out error
  req.on('error', function(err) {
    console.log('website name:' + url);
    console.log(err);
    console.log("\n");
    callback(err);
  });

  req.end();
}

Also, your options contains settings not available for http.request. They are for a third-party request module.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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