检测 Javascript/ECMAScript 等待滥用?

Detect Javascript/ECMAScript await misuse?

Javascript 或 Typescript 生态系统中是否有工具可以检测(mis/over)在同步函数上使用 await? (例如 tslint 规则)

同步函数的结果误用await时出现问题,

const decoded = await jsonwebtoken.verify(session, publicKey, opts);

我的 linter(默认的 gts tslint)没有捕捉到。代码奇怪地工作(await 默默地传递非承诺?),但我想标记滥用以鼓励使用 asynchonous/callback 选项。

我原以为 await 的这种误用会引发 Typescript 错误,但 tscts-jest 通过了以下测试:

test('Demonstrate await', async () => {
  function foo(): number { return 4; }
  const food = await foo(); // Even replace foo() with a constant or literal.
  expect(food).toBe(4);
});

如果 awaited 表达式不是 promise,则将其包裹在 promise 中,然后等待。

这意味着您可以放置​​对象、函数甚至基元,它会被视为承诺。

编辑源代码——在此处查看此讨论:https://github.com/Microsoft/TypeScript/issues/8310

await 作用于表达式。当表达式是一个 promise 时,异步函数的计算将停止,直到 promise 被解析。当表达式为非承诺值时,使用 Promise.resolve 将其转换为承诺,然后解析。

JS await:

If the value of the expression following the await operator is not a Promise, it's converted to a resolved Promise.

所以这并没有错,它可能对测试有用,也可能在实时代码中有用。

是的,如果您使用类型系统,则可以强制执行这样的 linter 规则。对于 TSlint,你可以使用这样的东西:

https://palantir.github.io/tslint/rules/await-promise/