[英]Javascript - avoiding asynchronous race condition when checking object property existence
Whilst JavaScript might not be multi-threaded, it does support asynchronous execution and whilst executions for 2 or more asynchronous bits of code might be on the same thread, the fact that an asynchronous order of events cannot be predicted, makes it possible for a race condition between asynchronous executions to occur. 尽管JavaScript可能不是多线程的,但它确实支持异步执行,并且2位或更多位异步代码的执行可能在同一线程上,但无法预测事件的异步顺序这一事实使比赛成为可能异步执行之间发生的条件。
I am doing an asynchronous check for the existence of an object property. 我正在异步检查对象属性的存在。 Said property will be assigned a large multi-dimensional child object - including child objects arrays, own properties etc.
会为该属性分配一个大型的多维子对象-包括子对象数组,自己的属性等。
In the example below, I already know the parent object exists, ie I know that myObject
exists. 在下面的示例中,我已经知道父对象存在,即,我知道
myObject
存在。 I want my check to return true
as soon as all the content of myObject['myObjectChildren']
is in place. 我希望我的检查一经
myObject['myObjectChildren']
所有内容就return true
。
To check for the existence of the object property, I do the following: 为了检查对象属性是否存在,我执行以下操作:
if(myObject.hasOwnProperty('myObjectChildren'))
return true;
The only way that myObject['myObjectChildren']
gets assigned is in the format, but this assignment is done asynchronously: 分配
myObject['myObjectChildren']
的唯一方法是采用格式,但是这种分配是异步完成的:
myObject['myObjectChildren'] = {
largeChildObject:{
grandchildren:[
{grandchild1:{
grandchild1GreatGrandChildren:[
grandchild1GreatGrandChild1:{},
grandchild1GreatGrandChild2:{}....
]
},
{grandchild2:{},
{grandchild3:{}....
]
}
};
MY QUESTION: 我的问题:
My question is, can I safely assume that as soon as myObject.hasOwnProperty('myObjectChildren') === true
, myObject['myObjectChildren']
has all the content assigned to it, bearing in mind it is assigned in one go. 我的问题是,我可以安全地假设
myObject.hasOwnProperty('myObjectChildren') === true
, myObject['myObjectChildren']
已分配了所有内容,请记住,它是一次性分配的。 Is there any circumstance where the check might fail? 在任何情况下检查可能会失败? eg on assignment, does the property get instantiated to
'undefined'
first? 例如,在赋值时,该属性是否首先被实例化为
'undefined'
?
Currently, my code is only returning true when all content for it is in place. 目前,我的代码仅在所有内容都到位时才返回true。 However, my concern is that I've inadvertently entered into a race condition.
但是,我担心的是我无意中进入了比赛状态。
由于javascript执行具有单线程性质,因此在所有值均分配到一个同步块中的情况下,在所有情况下您的检查都是正确的,因为执行分配时控制流无法“跳转”到您的检查逻辑。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.