TypeScript 中的异步/等待和承诺

Muh*_*uhy 7 javascript asynchronous async-await typescript

我试图理解为什么string以下方法中的返回类型带有红色下划线作为错误:

exportPageAsText(pageNumber: number): string {
        (async () => {
            const text = await this.pdfViewerService.getPageAsText(pageNumber);
            console.log(text);
            return text;
        })();
}
Run Code Online (Sandbox Code Playgroud)

错误消息如下:A function whose declared type is neither 'void' nor 'any' must return a value.所以我移出return text;范围async并将其放置在后面})();,但这使得text变量无法识别。

然后我想也许是因为方法返回类型应该是 aPromise所以我将签名更改为:

exportPageAsText(pageNumber: number): Promise<string>
Run Code Online (Sandbox Code Playgroud)

但我收到一个新错误说A function whose declared type is neither 'void' nor 'any' must return a value.

有人可以帮助我理解我做错了什么吗?

JSO*_*ulo 5

你想使用await,所以你需要一个异步函数。您创建的是一个自调用异步函数。但是在自调用函数内部返回一个值并不会为基函数返回该值。

您正在寻找的是使基本函数异步,并将返回类型设置为Promise<string>

async exportPageAsText(pageNumber: number): Promise<string> {
  const text = await this.pdfViewerService.getPageAsText(pageNumber);
  console.log(text);
  return text;
}
Run Code Online (Sandbox Code Playgroud)

  • 随后如何将 `Promise&lt;string&gt;` 转换为 `string`?在其他地方,我使用 `let text = this.pdfService.exportPageAsText(pageNumber);`,然后在 `text` 上使用 `.replace`,但是我当然得到一个错误,指出 `.replace` 是一个 `string` 方法,不是 `Promise&lt;string&gt;` 方法。我无法将其设为“异步”;它必须转换为普通的“字符串”,可以这么说...... (3认同)
  • 在这种情况下,您必须直接使用 Promise,例如 `this.pdfService.exportPageAsText(pageNumber).then(text =&gt; { console.log(text); })` (2认同)