【问题标题】:Why is @typescript-eslint/promise-function-async triggered by this code?为什么这段代码会触发@typescript-eslint/promise-function-async?
【发布时间】:2020-10-05 16:58:42
【问题描述】:

我的小项目中有这段代码:

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();
    }
}

当我在其上运行 xo(使用 typescript-eslint)时,@typescript-eslint/promise-function-async 失败。我做了一些更改,但仍然失败。谁能给我解释一下为什么这不起作用?

我尝试了什么:

// 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));

【问题讨论】:

  • 问题是@typescript-eslint/promise-function-async还是@typescript-eslint/restrict-template-expressions
  • 另外,规则可能希望你这样做this.state.queue.map(async (message) =&gt; this.sendAsync(message) );
  • 按照规则要求将返回 promise 的函数标记为异步?你读过github.com/typescript-eslint/typescript-eslint/blob/master/…吗?

标签: typescript eslint typescript-eslint


【解决方案1】:

这里是@typescript-eslint/promise-function-async规则的描述:

要求将任何返回 Promise 的函数或方法标记为异步。

不正确代码示例:

const arrowFunctionReturnsPromise = () => Promise.resolve('value');

function functionReturnsPromise() {
  return Promise.resolve('value');
}

正确代码:

const arrowFunctionReturnsPromise = async () => Promise.resolve('value');

async function functionReturnsPromise() {
  return Promise.resolve('value');
}

您的代码未能通过示例的第一行。更具体地说,问题在这里:

const sendPromises = this.state.queue.map((message) =>
  this.sendAsync(message)
);

你正在调用 .map() 并使用产生承诺的箭头函数,因此根据规则,你必须将其标记为 async,如下所示:

const sendPromises = this.state.queue.map(async (message) =>
//                                        ^^^^^
  this.sendAsync(message)
);

【讨论】:

    【解决方案2】:

    阅读 cmets 后,我注意到我应该将 async 添加到我的箭头函数中。

    具有讽刺意味的是,我之前修复了同样的错误,但我忽略了这个。

    感谢您的帮助。

    【讨论】:

      猜你喜欢
      • 2021-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-27
      • 1970-01-01
      • 2017-03-19
      • 2018-04-05
      • 1970-01-01
      相关资源
      最近更新 更多