-2

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

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

2 回答 2

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)
);
于 2020-06-16T07:05:25.950 回答
0

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

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

感谢您的帮助。

于 2020-06-16T07:04:22.807 回答