no-async-promise-executor
禁止使用异步函数作为 Promise 执行器
在 配置文件 中使用来自 @eslint/js
的 recommended
配置可以启用此规则
new Promise
构造函数接受一个执行器函数作为参数,该函数具有 resolve
和 reject
参数,可用于控制创建的 Promise 的状态。例如:
¥The new Promise
constructor accepts an executor function as an argument, which has resolve
and reject
parameters that can be used to control the state of the created Promise. For example:
const result = new Promise(function executor(resolve, reject) {
readFile('foo.txt', function(err, result) {
if (err) {
reject(err);
} else {
resolve(result);
}
});
});
执行器函数也可以是 async function
。但是,这通常是一个错误,原因如下:
¥The executor function can also be an async function
. However, this is usually a mistake, for a few reasons:
-
如果异步执行器函数抛出错误,错误将丢失,不会导致新构建的
Promise
拒绝。这可能会使调试和处理一些错误变得困难。¥If an async executor function throws an error, the error will be lost and won’t cause the newly-constructed
Promise
to reject. This could make it difficult to debug and handle some errors. -
如果 Promise 执行器函数使用
await
,这通常表明实际上不需要使用new Promise
构造函数,或者可以缩小new Promise
构造函数的范围。¥If a Promise executor function is using
await
, this is usually a sign that it is not actually necessary to use thenew Promise
constructor, or the scope of thenew Promise
constructor can be reduced.
规则详情
¥Rule Details
此规则旨在禁止异步 Promise 执行器功能。
¥This rule aims to disallow async Promise executor functions.
此规则的错误代码示例:
¥Examples of incorrect code for this rule:
/*eslint no-async-promise-executor: "error"*/
const foo = new Promise(async (resolve, reject) => {
readFile('foo.txt', function(err, result) {
if (err) {
reject(err);
} else {
resolve(result);
}
});
});
const result = new Promise(async (resolve, reject) => {
resolve(await foo);
});
此规则的正确代码示例:
¥Examples of correct code for this rule:
/*eslint no-async-promise-executor: "error"*/
const foo = new Promise((resolve, reject) => {
readFile('foo.txt', function(err, result) {
if (err) {
reject(err);
} else {
resolve(result);
}
});
});
const result = Promise.resolve(foo);
何时不使用
¥When Not To Use It
如果你的代码库不支持 async function
语法,则无需启用此规则。
¥If your codebase doesn’t support async function
syntax, there’s no need to enable this rule.
版本
此规则是在 ESLint v5.3.0 中引入。