【问题标题】:javascript synchronous asynchronous query [duplicate]javascript同步异步查询[重复]
【发布时间】: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?一个是同步的,另一个不是。
  • 阅读 readFilereadFileSync 的文档
  • “回调总是异步的吗?” 不。当内部代码决定是调用它的好时机时,回调就像任何其他函数一样在内部简单地被调用。这不需要涉及任何异步行为。

标签: javascript node.js asynchronous


【解决方案1】:

同步版本(fs.readFileSync)会阻塞执行,直到文件被读取并返回包含文件内容的结果:

var data = fs.readFileSync('input.txt');

这意味着在文件完全读取并将结果返回给数据变量之前,不会执行下一行代码。

另一方面(fs.readFile)的异步版本将立即将执行返回到下一行代码(即console.log("Program Ended");):

fs.readFile('input.txt', function(err, data) {
    // This callback will be executed at a later stage, when
    // the file content is retrieved from disk into the "data" variable
    console.log(data.toString());   
});

然后,当文件内容被完全读取时,将调用传递的回调,因此您会看到稍后打印的文件内容。建议使用第二种方法,因为您不会在文件 I/O 操作期间阻止代码的执行。这允许您同时执行更多操作,而同步版本将冻结任何其他执行,直到它完全完成(或失败)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-08
    • 2018-02-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多