2014-04-23 6 views
0

아래에 node.js 파일 호출 test.js가 있습니다. 왜 '모두 완료되었습니다!' 항상 출력 맨 위에 인쇄됩니다. 누군가가 '모두 완료되었습니다!'라는 이유를 설명 할 수 있습니까? 항상 콘솔의 첫 번째 출력이됩니다. 모든 요청이 완료되고 응용 프로그램을 종료 한 후 마지막 행으로 어떻게 인쇄 할 수 있습니까? setTimeout을 사용하여 'All done'을 마지막으로 만들려고했으나 각 요청의 완료 기간을 알 수 없으므로 도움이되지 않습니다. process.exit()를 사용해야합니까?Node.js 비동기 콜백 설명

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 
    } 

}); 

답변

1

getHeader 함수가 끝날 때 즉시 콜백을 호출합니다. 당신은 요구가 완료하면 대신 호출해야합니다

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(); 
} 

또한, 당신의 options는 http.request 사용할 수없는 설정이 포함되어 있습니다. 타사 request 모듈 용입니다.

+0

안녕하세요, Mscdex에서 "콜백 반환 (null);"을 (를) 제거했지만 "완료되었습니다"를 출력하지 않습니다. 사실, 모든 요청이 완료되었지만 전체 앱 훅. 요청이 완료 될 때까지 getHeader에서 콜백을 호출해야한다는 것을 이해하지만 그 논리를 어디에 두어야하는지는 알지 못합니다. 감사! – samuel890

+0

방금 ​​준 예제 코드는 여러분에게 보여줍니다. – mscdex

+0

내 부주의 .. http 요청에서 콜백()을 보지 못했습니다 .. – samuel890