我沒有用JavaScript太多的經驗和我下面一個Node.js的書,它有下面的代碼這個封閉是如何工作的?
function start(route, handle)
{
function onRequest(request, response)
{
var postdata='';
var pathname=url.parse(request.url).pathname;
request.setEncoding('utf8');
request.addListener("data", function(postDataChunkd)
{
postdata+=postDataChunkd;
});
console.log('Post data: ' + postdata);// <----------------------- HERE
request.addListener("end", function()
{
route(handle, pathname, response, postdata);
});
}
http.createServer(onRequest).listen(8124);
console.log('Server running on 8124');
}
exports.start=start;
代碼工作正常不過的事情是,對我來說這似乎是一個位隱晦的變量postData被記錄爲addListener(「data」...和addListener(「end」)中的空字符串...
有人可以解釋爲什麼postData變量記錄爲空,儘管成功請求?
Regards
丹
使用NodeJS時的一階業務就是熟悉異步編程的概念。您正在爲'data'事件添加一個偵聽器,並且清楚地知道,當您的'console.log()'運行時事件還沒有發生。 – 2014-10-09 17:13:05
...將日誌*放置在事件處理程序中,您將獲得有意義的結果。 – 2014-10-09 17:14:17
當然,我會更加關注異步方面。謝謝 – user3256539 2014-10-09 19:05:09