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

Understanding control flow in Node.js applications

本文关键字:控制流 应用程序 Node js 了解      更新时间:2023-09-26

我正在尝试了解 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 请求是异步的。