와 HTTP 요청 후 차단하는 나는 다음과 같은 코드가 있습니다어떻게 Node.js를
var options1 = {
host: 'maps.googleapis.com',
port: 80,
path: "/maps/api/geocode/json?latlng=" + lat + "," + lng + "&sensor=false",
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
};
var body1 = "";
var req = http.request(options1, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function (chunk) {
//console.log('BODY: ' + chunk);
body1 += chunk;
});
res.on('close', function() {
console.log('get_zillow : ' + body1);
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
req.end();
console.log('get_zillow : ' + body1);
내가 JSON 응답의 결과 body1을 채울 필요가 있습니다. 그러나 첫 번째 console.log('get_zillow : ' + body1);
은 호출되지 않습니다. 어떤 이유로 든 결과가 닫히지 않습니다. 두 번째 console.log('get_zillow : ' + body1);
은 아무 것도 출력하지 않습니다. 이는 비동기이며 body1
이 채워지기 전에 호출되기 때문에 아무 것도 인쇄하지 않습니다.
또한 여러 외부 사이트에 유사한 요청을 여러 번 연속하여 수행해야하며 각 요청은 이전 결과의 json에 따라 달라집니다. 세 가지 지저분한 내부 콜백을 작성하지 않고이를 수행 할 수있는 방법이 있습니까? 그리고 http 요청 후에 차단하는 방법이 있습니까? // 새로운 함수를 정의
, 나는 대답은 알고있다 부정적인 것. –
콜백 (AFAIK)을 피할 수는 없지만 콜에서 인라인 대신 콜백을 제공하여 중첩을 피할 수 있습니다. –
[' 'end''] (http://nodejs.org/api/ http : // http : //nodejs.org/api/http.html#http_event_close_3)보다는 [http : //www.html # http_event_end_1]을 사용하십시오. 그리고 비동기 작업을 위해 차단을 강요 할 수 없습니다. 그러나 [흐름 제어] (https://encrypted.google.com/search?q=async+flow+control&q=site:npmjs.org&hl=ko) 및 [약속/선물] (https : // 암호화 됨. google.com/search?q=promises+futures&q=site:npmjs.org&hl=en) [async'] (https://npmjs.org/package/async)와 같은 도움을 줄 수있는 라이브러리 (특히 [ async.waterfall'] (https://npmjs.org/package/async#waterfall)). –