gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 11:52:18 26 4
gpt4 key购买 nike

我刚刚修复了一个错误,在该错误中我使用 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/

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