javascript - 从 `void` 函数返回 `async`

标签 javascript typescript

所以我现在遇到过几次这个问题,但我总是忽略它。

当我编码时在 TypeScript 中:

async function someAsyncFunc(): void {
    const prom = await somePromise();
}

它向我提示异步函数应该始终具有返回类型:Promise<T> 。所以它想从我这里得到的是:

async function someAsyncFunc(): Promise<void>

我知道,但这个方法不会返回任何内容。到目前为止,我总是屈服并使用类型 Promise<void>但这会导致错误,因为 TypeScript 现在认为这个函数返回一个 promise ,不是吗?

在写这个问题时有一个想法并进行了测试..结果是正确的。如果您想知道的话,请查看我自己的答案:)

错误消息,因此它有望被谷歌索引:

The return type of an async function or method must be the global Promise<T> type.

最佳答案

异步函数被视为 Promise paradigm 的扩展.

对于 javascript/typescript,知道特定函数的返回是异步的,因为它返回一个 Promise。这意味着异步函数返回类型始终为 Promise。然后,您可以将一个值包装到该 Promise 中,该值可以是 voidnumberstring、另一个 promise,等等

来自MDN :

An asynchronous function is a function which operates asynchronously via the event loop, using an implicit Promise to return its result.

更多内容:

An async function can contain an await expression that pauses the execution of the async function and waits for the passed Promise's resolution, and then resumes the async function's execution and returns the resolved value. Remember, the await keyword is only valid inside async functions.

恢复:函数中的 aysnc/await 是语法糖,以提高代码的可读性。

关于javascript - 从 `void` 函数返回 `async`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60761684/

相关文章:

javascript - 检查一个对象是否存在于数组中其他对象的子对象中

typescript - Typescript 编译器是否公开了 JsDoc @param 的默认值?

reactjs - 组件安装时 Ref.current 未定义,当我需要它时它不会导致重新渲染

angular - 将 HTML5 <audio> 标签的控件绑定(bind)到 Angular 中的自定义按钮

javascript - 我如何处理jquery中的多个ajax错误

javascript - history.pushState 不更新移动 Chrome 上 "share ..."按钮的 url

javascript - Python while 循环转换为 Javascript

javascript - 外部链接到选项卡、选项卡未更改、Bootstrap 3.3.5

javascript - Angular 2 - 根据输入值在模板中添加属性

reactjs - 将 Polymer Web Components 集成到用 Typescript 编写的 React 应用程序中?