gpt4 book ai didi

javascript - 将自定义方法分配给 WebSocket 时如何避免竞争条件?

转载 作者:行者123 更新时间:2023-11-30 14:16:19 24 4
gpt4 key购买 nike

当我查看有关 WebSocket 的教程/文档时,我发现类似 this 的代码:

var ws = new WebSocket("ws://localhost:8765/dlt");
ws.onopen = () => {
// do some very important stuff after connection has been established
console.log("onopen");
}

但是这里的竞争条件呢?在 JavaScript 中是否以某种方式避免了?

例如,此代码(仅分配 onopen after 连接已打开)将失败:

var ws = new WebSocket("ws://localhost:8765/dlt");
setTimeout(() => {
ws.onopen = () => {
// do some very important stuff after connection has been established
console.log("onopen"); /// <== won't be called
}
}, 100);

我可以确定在连接建立之前分配已经完成吗?

(我尝试使用自定义的 onopen() 方法扩展 WebSocket 但这似乎不起作用)

class MyWebSocket extends WebSocket {
onopen() {
console.log("onopen()");
/// do some very important stuff after connection has been established
}
}

最佳答案

您应该阅读有关 javascript 事件循环的文章:https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop#Event_loop

如果您查看有关Run-to-completion 的部分,您会得到以下有用的解释:

Each message is processed completely before any other message is processed. This offers some nice properties when reasoning about your program, including the fact that whenever a function runs, it cannot be pre-empted and will run entirely before any other code runs (and can modify data the function manipulates). This differs from C, for instance, where if a function runs in a thread, it may be stopped at any point by the runtime system to run some other code in another thread.

因此,在您的示例中,对 ws.onopen 的分配必须在 websocket 执行本质上异步的任何操作之前完成。通过将您的分配放在 setTimeout 中,您将它移出当前运行的上下文,因此它可能不会在 websocket 需要之前执行。

关于javascript - 将自定义方法分配给 WebSocket 时如何避免竞争条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53519021/

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