对于learnyounode node.js教程,console.log打印语句的顺序错误 [英] console.log printing statements in the wrong order for learnyounode node.js tutorial

查看:111
本文介绍了对于learnyounode node.js教程,console.log打印语句的顺序错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作 GET 请求,存储数据,然后注意响应结束。我有一个 console.log 语句,当我完成接收数据时,另一个语句用于程序完成时。见下文:

I'm making a GET request, storing the data, and then noting the response is over. I have one console.log statement for when I'm done receiving the data and another for when the program has finished. See below:

var a = 1
var b = 10e9

http.get(process.argv[2], function(response){
  response.pipe(bl())
  response.on('end', function(){
    console.log("Finished receiving data")
  })
})

while(a != b){
  a++
}

console.log("Program has finished")

在这种情况下,我希望订单打印报表

In this case, I would expect the order of the print statements to be

Finished receiving data
Program has finished

因为我希望响应的结束发生在之前,而循环终止。但是,无论该循环是1还是1还是1到100000000000,我总是得到

because I would expect the end of the response to occur before the while loop terminates. However, regardless of whether that loop is 1 to 2 or 1 to 100000000000, I always get

Program has finished
Finished receiving data

为什么打印报表按此顺序发生?

Why are the print statements happening in this order?

推荐答案

对于其异步表达性的所有大惊小怪,node.js是单线程的,每个进程只有一个执行线程 - 这意味着只有一行代码将一次执行。

For all of the fuss about its asynchronous expressivity, node.js is single threaded and will only have one thread of execution per process - that means only one line of code will be executed at a time.

当您对 http.get 进行异步调用时,node.js发送HTTP GET并延迟回调的执行,直到(1)回调准备好被调用,(2)它用完了同步(阻塞)代码来运行。这就解释了为什么你总是看到程序完成首先 - node.js已经完成执行其阻塞代码并准备继续处理包含<$的异步回调c $ c>完成接收数据。

When you make the asynchronous call to http.get, node.js sends off an HTTP GET and defers execution of the callback until (1) the callback is ready to be called and (2) it runs out of synchronous (blocking) code to run. This explains why you always see "Program is finished" first - node.js has finished executing its blocking code and is ready to move on to handling the asynchronous callback that contains "Finished receiving data".

这篇关于对于learnyounode node.js教程,console.log打印语句的顺序错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆