[英]Why does boolean assignment after await triggers atomic update error?
let searching = false;
const search = async () => {
if (searching) {
throw new Error('No parallel process allowed.');
}
try {
searching = true;
const result = await someAsyncMethod();
searching = false;
return result;
} catch (e) {
searching = false;
throw e;
}
};
The above code will generate an atomic updates error in vscode
saying "Possible race condition: searching
might be reassigned based on an outdated value of searching
" on the line 10 searching = false
.上面的代码将在
vscode
生成一个原子更新错误,在第 10 行vscode
searching = false
上说“可能的竞争条件: searching
可能会根据过时的searching
值重新分配”。
Why?为什么? Does it actually create data race?
它真的会造成数据竞争吗?
ESLint isn't smart enough to recognize the significance of the searching
variable. ESLint 不够聪明,无法识别
searching
变量的重要性。 The conditions for the rule violation are :违反规则的条件是:
The logic ESLint sees is something like: "If searching is false when the function is called, reassign searching after an asynchronous method." ESLint 看到的逻辑是这样的:“如果在调用函数时搜索为假,则在异步方法之后重新分配搜索。” It's warning that something else might have reassigned searching to true after the function was called, but before the
await
resolved, in which case reassigning after the await
will be doing something based on the outdated value, which may not be desirable.这是警告,在调用函数之后,但在
await
解决之前,其他东西可能已将搜索重新分配为 true,在这种情况下,在await
之后重新分配将根据过时的值执行某些操作,这可能是不可取的。
The following code without searching = true
throws the same warning:以下代码没有
searching = true
会抛出相同的警告:
let searching = false;
const search = async () => {
if (searching) {
throw new Error('No parallel process allowed.');
}
try {
const result = await someAsyncMethod();
searching = false;
return result;
} catch (e) {
searching = false;
throw e;
}
};
Despite your logic being sound, ESLint can't determine your exact intent.尽管您的逻辑是合理的,但 ESLint 无法确定您的确切意图。 Feel free to disable the rule here.
随意禁用这里的规则。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.