【问题标题】:async/await and promise in TypeScriptTypeScript 中的 async/await 和 promise
【发布时间】:2021-10-29 14:27:55
【问题描述】:

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

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

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

然后我想可能是因为方法返回类型应该是Promise所以我将签名更改为:

exportPageAsText(pageNumber: number): Promise<string>

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

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

【问题讨论】:

  • 我认为当你这样做时:(async () =&gt; {,你正在创建一个新函数,所以这个函数应该有一个返回类型
  • 你没有返回任何东西,只是执行箭头异步函数。只需在 (async()=>...) 之前添加 return。

标签: javascript typescript asynchronous async-await


【解决方案1】:

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

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

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

【讨论】:

  • 我如何随后将Promise&lt;string&gt; 转换为string?在其他地方,我使用let text = this.pdfService.exportPageAsText(pageNumber);,然后在text 上使用.replace,但当然我得到一个错误,.replacestring 方法,而不是Promise&lt;string&gt; 方法。我不能做那个async;它必须转换为普通的string,可以这么说......
  • 在这种情况下,您必须直接使用 Promise,例如 this.pdfService.exportPageAsText(pageNumber).then(text =&gt; { console.log(text); })
【解决方案2】:

您的方法在结束前等待返回,但事件 async () => {... 声明的承诺没有返回

在你的代码中有两件事要改变

  1. 返回 async()
  2. 将方法声明中的返回类型更改为Promise&lt;string&gt;

在你的情况下,它看起来像

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

【讨论】:

    【解决方案3】:

    这就是我会做的。异步/等待。

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

    【讨论】:

      猜你喜欢
      • 2016-02-26
      • 2023-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-22
      • 2019-11-05
      • 2021-05-13
      • 1970-01-01
      相关资源
      最近更新 更多