簡體   English   中英

了解Node.js應用程序中的控制流

[英]Understanding control flow in Node.js applications

我試圖了解Node.js應用程序中的控制流。 明確地說,一旦回調方法完成(例如遞歸調用中的回調堆棧),控件就會返回到原始函數。 我編寫了一個簡單的程序,該程序進行GET調用並返回數據。 這是程序:

碼:

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

function getGoogleData(url, callback) {
    http.get(url, function(response) {
        if (response.statusCode == 200) {
            var googleInfo = '';
            response.on('data', function(chunk) {
                console.log("receiving data... ");
                googleInfo += chunk;
                return;
            });
            response.on('end', function() {
                console.log("End of data receive... ");
                response.setEncoding('utf8');
                return callback(null, googleInfo);
            });
        }
        console.log("I am here but why!");
        //callback(new Error("GET called failed status_code=" + response.statusCode));
    });
    console.log("Return from get google data");
}

async.waterfall([
    function(callback) {
        console.log("In func 1");
        getGoogleData("http://www.google.com", callback);
    },
    function(data, callback) {
        console.log("In func 2");
        callback(data);
    }],
    function (err, res) {
        console.log("In err fn");
    });

這是程序的輸出:輸出:

In func 1
Return from get google data
I am here but why!
receiving data...
receiving data...
End of data receive...
In func 2
In err fn

有人可以幫助我理解為什么“我在這里但是為什么!” 即使從“數據”事件發射器返回后,該行仍被打印為控制台日志中的第二條輸出行? 這里的總體控制流程是什么?

您看到該消息首先記錄的原因是, if塊中正在執行的所有代碼都在添加事件處理程序。 在您的console.log已經執行之后,這些事件將在將來的某個時間發出。

這是類似的原因,因為HTTP請求是異步的,因此在請求完成之前就打印了“從獲取Google數據返回”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM