gpt4 book ai didi

node.js:回调顺序困惑

转载 作者:太空宇宙 更新时间:2023-11-04 02:33:43 24 4
gpt4 key购买 nike

我刚刚开始使用node.js。我发现它使用的异步编码风格确实令人印象深刻。然而,对于我们这些习惯了 Java 和 Python 的人来说,确实需要一些时间来适应。

我知道下面的代码可以正常工作。这个论坛上的几个问题都验证了这一点。我自己也尝试过。

var http = require('http'),
fs = require('fs');
fs.readFile('./index.html', function (err, html) {
if (err) {
//throw err;
}
http.createServer(function(request, response) {
console.log("Server started");
response.writeHeader(200, {"Content-Type": "text/html"});
response.write(html);
response.write("Other things");
response.end();
}).listen(3000);
});

我的解释方式如下:

1. Try reading the html file
i. When done create a server
ii. Send it over to the client
2. Do everything else.

但是,我们也可以有如下的一系列思考:

1. Create the server
2. Try reading the file
i. When done. Send it over to the client
3. In the meanwhile do anything else the server might be asked to do.

第二条思路对应的代码是:

var http = require('http'),
fs = require('fs');

http.createServer(function(request, response) {
console.log("Server started");
response.writeHeader(200, {"Content-Type": "text/html"});
fs.readFile('./index.html', function (err, html) {
if (err) {
//throw err;
}
response.write(html);
response.write("Other things");
});
response.end();
}).listen(3000);

第一个代码按预期工作。第二个在浏览器中根本不显示任何内容。

为什么第二条思路是错误的?

最佳答案

实际上,这里发生的是每次有传入请求时都会调用以下函数:

function(request, response) { 
console.log("Server started");
response.writeHeader(200, {"Content-Type": "text/html"});
response.write(html);
response.write("Other things");
response.end();
}

您将其替换为:

function(request, response) { 
console.log("Server started");
response.writeHeader(200, {"Content-Type": "text/html"});
fs.readFile('./index.html', function (err, html) {
if (err) {
//throw err;
}
response.write(html);
response.write("Other things");
});
response.end();
}

现在,它将运行以下命令:

  1. 编写标题
  2. 对读取文件进行排队
  3. 立即执行以下代码:response.end();
  4. 当它完成读取文件并想要写入内容时,您已经结束了响应

关于node.js:回调顺序困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24444325/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com