简体   繁体   English

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

[英]Understanding control flow in Node.js applications

I am trying to understand control flow in Node.js applications. 我试图了解Node.js应用程序中的控制流。 Specifically does control returns to the original function once callback method completes (like a callback stack in recursive calls). 明确地说,一旦回调方法完成(例如递归调用中的回调堆栈),控件就会返回到原始函数。 I wrote a simple program that make a GET call and return the data. 我编写了一个简单的程序,该程序进行GET调用并返回数据。 Here is the program: 这是程序:

Code: 码:

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

Here is output of the program: Output: 这是程序的输出:输出:

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

Can someone help me understand why 'I am here but why!' 有人可以帮助我理解为什么“我在这里但是为什么!” line gets printed as the second output line in console log even after returning from 'data' event emitter? 即使从“数据”事件发射器返回后,该行仍被打印为控制台日志中的第二条输出行? What is the overall control flow here? 这里的总体控制流程是什么?

The reason you're seeing that message logged first is that all that the code inside the if block is doing is adding event handlers. 您看到该消息首先记录的原因是, if块中正在执行的所有代码都在添加事件处理程序。 Those events are emitted some time in the future, after your console.log has already executed. 在您的console.log已经执行之后,这些事件将在将来的某个时间发出。

It's a similar reason why "Return from get google data" gets printed before the request finishes, because the http request is asynchronous. 这是类似的原因,因为HTTP请求是异步的,因此在请求完成之前就打印了“从获取Google数据返回”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM