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.
有人可以帮助我理解我做错了什么吗?
你想使用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)
归档时间: |
|
查看次数: |
15843 次 |
最近记录: |