【发布时间】:2017-09-20 04:07:10
【问题描述】:
我是 Javascript 新手。
nodejs下面代码同步运行,我不明白,为什么?
var http = require("http");
var fs = require("fs");
http.createServer(function (request, response) {
// Send the HTTP header
// HTTP Status: 200 : OK
// Content Type: text/plain
response.writeHead(200, {'Content-Type': 'text/plain'});
// Send the response body as "Hello World"
response.end('Hello World\n');
}).listen(8081);
// Console will print the message
console.log('Server running at http://127.0.0.1:8081/');
var data = fs.readFileSync('input.txt');
console.log(data.toString());
console.log("Program Ended");
我得到的输出为:
Server running at http://127.0.0.1:8081/
Tutorials Point is giving self learning content
to teach the world in simple and easy way!!!!!
Program Ended
下面nodejs代码异步运行,我不明白,为什么?我同意 readFile 函数中有一个回调,为什么它的行为是异步的?
var http = require("http");
var fs = require("fs");
http.createServer(function (request, response) {
// Send the HTTP header
// HTTP Status: 200 : OK
// Content Type: text/plain
response.writeHead(200, {'Content-Type': 'text/plain'});
// Send the response body as "Hello World"
response.end('Hello World\n');
}).listen(8081);
// Console will print the message
console.log('Server running at http://127.0.0.1:8081/');
fs.readFile('input.txt', function(err, data){
console.log(data.toString());
});
console.log("Program Ended");
这是输出:
Server running at http://127.0.0.1:8081/
Program Ended
Tutorials Point is giving self learning content
to teach the world in simple and easy way!!!!!
请有人清楚地解释一下为什么上面的行为会这样。回调总是异步的吗?我也想知道回调函数的内部执行是如何发生的。
假设一个控件来到readFile 函数(其中包含回调),那么为什么控件会立即执行另一个语句?如果控制转移到另一个语句,谁来执行回调函数?回调返回某个值后,控制是否再次返回到相同的语句,即“readFile”行?
对不起,愚蠢的查询。
【问题讨论】:
-
显而易见的答案是因为
readFile函数就是这样设计的。那你问为什么需要异步版本的函数? -
回调不会使异步代码同步运行。它只是为您提供了一种从中断处继续执行流程的方法。
-
您是否注意到第一个示例使用 readFileSync 而第二个示例使用 readFile?一个是同步的,另一个不是。
-
阅读 readFile 和 readFileSync 的文档
-
“回调总是异步的吗?” 不。当内部代码决定是调用它的好时机时,回调就像任何其他函数一样在内部简单地被调用。这不需要涉及任何异步行为。
标签: javascript node.js asynchronous