简体   繁体   English

为什么等待后布尔赋值会触发原子更新错误?

[英]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 :违反规则的条件

  • A variable or property is reassigned to a new value which is based on its old value.一个变量或属性被重新分配给一个基于其旧值的新值。
  • A yield or await expression interrupts the assignment after the old value is read, and before the new value is set.在读取旧值之后和设置新值之前,yield 或 await 表达式会中断赋值。
  • The rule cannot easily verify that the assignment is safe (eg if an assigned variable is local and would not be readable from anywhere else while the function is paused).该规则无法轻松验证赋值是否安全(例如,如果已赋值的变量是本地变量并且在函数暂停时无法从其他任何地方读取)。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM