我是否需要关注异步Javascript的竞争条件? [英] Do I need to be concerned with race conditions with asynchronous Javascript?

查看:109
本文介绍了我是否需要关注异步Javascript的竞争条件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我加载了一些我以后知道的Flash电影将调用 window.flashReady 并设置 window.flashReadyTriggered = true

Suppose I load some Flash movie that I know at some point in the future will call window.flashReady and will set window.flashReadyTriggered = true.

现在我有一段代码,我想在Flash准备就绪时执行。如果 window.flashReady 已被调用,我希望它立即执行它我想把它作为回调放在 window.flashReady 如果尚未调用。天真的方法是:

Now I have a block of code that I want to have executed when the Flash is ready. I want it to execute it immediately if window.flashReady has already been called and I want to put it as the callback in window.flashReady if it has not yet been called. The naive approach is this:

if(window.flashReadyTriggered) {
  block();
} else {
  window.flashReady = block;
}

所以基于此的担忧是<$ $中的表达式c $ c> if 条件评估为 false ,但之后 block()可以执行, window.flashReady 由外部Flash触发。因此,永远不会调用

So the concern I have based on this is that the expression in the if condition is evaluated to false, but then before block() can be executed, window.flashReady is triggered by the external Flash. Consequently, block is never called.

是否有更好的设计模式来实现更高级别的目标我是去(例如,手动调用 flashReady 回调)?如果没有,我是安全的,还是我应该做的其他事情?

Is there a better design pattern to accomplish the higher level goal I'm going for (e.g., manually calling the flashReady callback)? If not, am I safe, or are there other things I should do?

推荐答案

JavaScript是单线程的。没有竞争条件。

JavaScript is single threaded. There are no race conditions.

当你的当前指令指针没有更多的代码要执行时,线程传递接力棒,并排队 window.setTimeout 或事件处理程序可以执行其代码。

When there is no more code to execute at your current "instruction pointer", the "thread" "passes the baton", and a queued window.setTimeout or event handler may execute its code.

您将更好地理解Javascript的单线程方法阅读 node.js 的设计思路。

You will get better understanding for Javascript's single-threading approach reading node.js's design ideas.

进一步阅读:
为什么JavaScript不支持多线程?

这篇关于我是否需要关注异步Javascript的竞争条件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆