[英]Why is @typescript-eslint/promise-function-async triggered by this code?
I have this code in my little project:我的小项目中有这段代码:
close(flush = false): void {
if (this.ws?.CLOSING || this.ws?.CLOSED) {
return;
}
if (flush) {
// I really don't know how to fix that
// eslint-disable-next-line @typescript-eslint/promise-function-async
const sendPromises = this.state.queue.map((message) =>
this.sendAsync(message)
);
void Promise.all(sendPromises).then(() => this.ws?.close());
} else {
this.ws?.close();
}
}
When I run xo
(which uses typescript-eslint) on it, @typescript-eslint/promise-function-async
fails.当我在其上运行
xo
(使用 typescript-eslint)时, @typescript-eslint/promise-function-async
失败。 I made a few changes, but it still fails.我做了一些更改,但仍然失败。 Can anyone give me an explanation about why this doesn't work?
谁能给我解释为什么这不起作用?
What I tried:我尝试了什么:
// first
const sendPromises: Promise<void> = this.state.queue.map((message) => this.sendAsync(message));
// second
const sendPromises = this.state.queue.map((message): Promise<void> => this.sendAsync(message));
Here is the description of the @typescript-eslint/promise-function-async
rule:这是
@typescript-eslint/promise-function-async
规则的描述:
Requires any function or method that returns a Promise to be marked async.
需要将任何 function 或返回 Promise 的方法标记为异步。
With example for incorrect code:以错误代码为例:
const arrowFunctionReturnsPromise = () => Promise.resolve('value');
function functionReturnsPromise() {
return Promise.resolve('value');
}
and correct code:和正确的代码:
const arrowFunctionReturnsPromise = async () => Promise.resolve('value');
async function functionReturnsPromise() {
return Promise.resolve('value');
}
Your code fails the first line of the example.您的代码未能通过示例的第一行。 More specifically the problem is here:
更具体地说,问题在这里:
const sendPromises = this.state.queue.map((message) =>
this.sendAsync(message)
);
You're calling .map()
with an arrow function that produces a promise, so according to the rule, you have to mark it as async
like so:您使用箭头 function 调用
.map()
,该箭头会产生 promise,因此根据规则,您必须将其标记为async
,如下所示:
const sendPromises = this.state.queue.map(async (message) =>
// ^^^^^
this.sendAsync(message)
);
After I read the comments I noticed that I should add async
to my arrow function.阅读评论后,我注意到我应该在箭头 function 中添加
async
。
Ironically, I fixed the same error before but I overlooked this one.具有讽刺意味的是,我之前修复了相同的错误,但我忽略了这个错误。
Thanks for helping.感谢您的帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.