Javascript 如何从indexedDB回调中修改全局变量?

Javascript 如何从indexedDB回调中修改全局变量?,javascript,html,asynchronous,indexeddb,Javascript,Html,Asynchronous,Indexeddb,我正在启动一系列indexeddb操作,希望它们能够在完成时增加一个计数器(以及更改一些其他内容,但对于这个问题,只需假设它正在增加一个计数器)。我从中知道,它在不同的线程中运行回调(尽管,尽管有这样的措辞,我不确定实现是否必须使用线程)。但话说回来,JavaScript/HTML5并不能保证某些东西的线程安全,所以我担心以下情况: /* Sequence involved in incrementing a variable "behind the scenes" */ //First cal

我正在启动一系列indexeddb操作,希望它们能够在完成时增加一个计数器(以及更改一些其他内容,但对于这个问题,只需假设它正在增加一个计数器)。我从中知道,它在不同的线程中运行回调(尽管,尽管有这样的措辞,我不确定实现是否必须使用线程)。但话说回来,JavaScript/HTML5并不能保证某些东西的线程安全,所以我担心以下情况:

/* Sequence involved in incrementing a variable "behind the scenes" */
//First callback calls i++; (it's 0 at this point)
load r0,[i]  ; load memory into reg 0

//Second callback calls i++ (it's still 0 at this point)
load r1,[i]  ; load memory into reg 1

//First callback's sequence continues and increments the temporary spot to 1
incr r0      ; increment reg 0

//Second callback's sequence continues and also increments the temporary spot to 1
incr r1      ; increment reg 1

//First callback sequence finishes, i === 1
stor [i],r0  ; store reg 0 back to memory


//Second callback sequence finishes, i === 1
stor [i],r1  ; store reg 1 back to memory
(或类似的东西)

那么我有什么选择呢?我是否可以在调用
postMessage
的每个回调中生成web工作者,然后侦听器将其递增?比如:

increment.js(我们的员工代码)

main.js

//Our "thread-safe" worker?
var incrementer = new Worker( "increment.js" );

//Success handler (has diff thread)
req.onsuccess = function(event) {  

    ...finish doing some work...

    //Increment it
    incrementer.postmessage( 1 );
};

这样行吗?或者web工作者的onmessage仍然会出现在回调的线程中?有没有办法让它进入全局线程

在参考文档中唯一提到的“线程”一词是IndexedDB API方法没有阻止调用线程(这仍然不意味着这些方法在单独的线程中运行,尽管它只是说明这些方法本质上是异步的),但是没有提到回调将在不同的线程中运行

另外,JavaScript本身是单线程的,因此您可以安全地假设回调都将在同一个(“全局”)线程中运行,并且将按顺序调用,而不是并发调用

因此不需要Web工作者,您可以直接从回调本身增加全局变量:

req.onsuccess = function(event) {  
  count += event.data;
};

但它经常使用“异步”一词,这意味着事情可以无序完成<代码>“异步执行请求的3.3.5步骤”。这难道不意味着可能存在比赛条件吗?如果规范中没有指定竞态条件,那么如何保证异步的东西没有竞态条件呢?@DonRhummy“竞态条件”不是由线程安全解决的。如果您希望异步操作保持其顺序,或者至少以启动这些操作的顺序结束结果,那么必须有某种协调代码(如can提供的);但是,这仍然不依赖于线程或线程安全原语/操作。对不起,这意味着我在最初的帖子中提到的竞争条件。我只是担心确实存在线程,并且不能保证回调不能无序访问。@DonRhummy正如我所写的,所有常见的JS运行时(浏览器、节点)都是单线程的,所以就线程安全而言,您不必担心。
req.onsuccess = function(event) {  
  count += event.data;
};