javascript - Node.js readline 行事件回调保证在下一次调用之前完成?

标签 javascript node.js readline

我刚刚修复了一个错误,在该错误中我使用 readline 读取和重写文件并且行被乱序写入(最终是由于异步 fs.write() 调用)。

但我认为正在发生的一件事是 readline line事件以正确的顺序进入,但也许我对某些行的回调函数在处理另一个 line 事件后完成。

演示:

line1 event comes in
line1 event finishes handling
line2 event comes in //Takes a long time to process
line3 event comes in
line3 event finishes handling
line2 event finished handling //And because it was after line3, gets written back after too

上面的最终文件输出如下:

line1
line3
line2

我没有在文档中看到任何此类保证,我的测试似乎表明上述情况是不可能的,但我不确定。 readline 是否可以实现上述场景?

最佳答案

NodeJS 在单个事件循环上运行您的 JavaScript 代码,JavaScript 规范称之为作业队列。这意味着当您的代码正在运行以响应第 2 行时,保证不会在它仍在运行时调用它来响应第 3 行——如果该事件在您的代码运行时发生,则调用您的回调的作业会排队但会等待作业排队直到您完成,事件循环可以选择队列中的下一个作业。

显然,这仅适用于同步代码,因为异步事物(如fs.write)仅启动一个进程,它们不'等待它完成;完成是添加到队列中的作业。因此,异步调用的回调很可能发生在下一个事件到来之后。

例如,考虑这段代码:

stream.on("line", function() {
    // do a lot of synchronous work that may tie up the thread for a while
});

您可以确定当第 3 行仍在处理第 2 行的回调时不会调用您的回调。

但是在处理第 2 行的回调时:

stream.on("line", function() {
    // Code here IS guaranteed to run before we get called for line 3
    callAnAsyncFunction(function(err, data) {
        // Code here is NOT guaranteed to run before we get called for line 3
    });
    // Code here IS guaranteed to run before we get called for line 3
});

关于javascript - Node.js readline 行事件回调保证在下一次调用之前完成?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39106895/

相关文章:

javascript - 在同一页面上多次运行 Greasemonkey 脚本?

bash - 如何在没有 Readline 支持的情况下在 bash 实例中设置不区分大小写的完成

ruby-on-rails - 在 Ubuntu Lucid Lynx 上安装 Heroku 失败

readline - 将 readline 接口(interface)到 Rust

node.js - 如何在我的服务器上的控制台中访问我的nodeJS应用程序?

node.js - (Discord.js) 如何标记机器人本身

javascript - 使用 Kong 的安全 api

javascript - 有没有办法从 jQuery Filterizr 获取事件类别?

javascript - 将 Select 2 与 ASP.NET MVC 结合使用

node.js - nodejs ejs View 引擎,一次将相同的参数传递给不同的路由?