我偶尔会忘记使用await关键字,例如:
I occasionally forget to use the await keyword, e.g.:
const foo = bar(); // instead of const foo = await bar();这些错误很难发现.可以使用哪些方法,库或工具来防止此类错误?
Those bugs are difficult to spot. Which methods, libraries or tools are available to prevent those kind of bugs?
推荐答案您应该使用诸如 ESLint 之类的短绒.如果将该工具与IDE/Editor集成在一起,并且启用了默认规则集(或您自己的规则集),它将使您的工作变得更加轻松.
You should use a linter like ESLint. If you integrate the tool with your IDE/Editor and you enable the default set of rules (or your own) it'll make your life a lot easier.
我很确定您的示例符合规则无浮动承诺,这会在没有适当处理的情况下禁止使用承诺.在您的情况下, bar()返回一个承诺,但是没有 await 或 then 来处理结果.
I'm pretty sure your example falls into the rule no-floating-promises, which disallows the usage of promises without proper handling. In your case bar() returns a promise but there's no await or then to handle the result.
要启用该规则,您必须安装ESLint以及 typescript-eslint 插入.我也强烈建议您在JavaScript上使用TypeScript,因为它会在开发过程中捕获一系列错误,并且您可以将TS代码转换为常见的JS代码.
To enable that rule you'll have to install ESLint plus the typescript-eslint plugin. I'll also strongly recommend you to use TypeScript over JavaScript, since it'll catch a series of bugs during development and you can transpile your TS code into common JS code.
更多推荐
在JavaScript中产生新型错误
发布评论