【问题标题】:Non-returning async method非返回异步方法
【发布时间】:2018-06-10 19:56:35
【问题描述】:

我使用的是Typescript,以es2017为编译目标,使用Javascript新的async/await

我目前有以下代码从 TS 服务类(简化)中获取一些数据:

class MyClass {

    public static async initialize(): Promise<void> {
        const data = await this.getItems();
        // do unrelated initialization stuff
        return new Promise<void>(() => {});
    }

    private static async getItems(): Promise<Item[]> {
        return await Service.fetchData();
    }
}

class Service {
    public static async fetchData(): Promise<Item[]> {
        // Performs an XHR and returns a Promise.
    }
}

这行得通,但是如果MyClass::initialize() 没有返回任何东西,而不是返回new Promise&lt;void&gt;(() =&gt; {});,它会干净得多。但是,这似乎是不可能的,因为任何使用await 的方法/函数都有 标记为async,并且任何标记为async 的方法/函数必须返回promise

有什么办法可以解决这个问题,还是有什么我根本没有掌握的东西?

【问题讨论】:

  • “必须返回一个承诺”不适用于 js。 JavaScript async 函数自动返回一个promise,函数的返回值(不一定是promise)解析调用函数时返回的promise。 Typescript 有什么不同吗?
  • 你不应该写一个只有静态方法的class。请改用对象字面量。
  • @Bergi 为什么会这样?
  • @Niek A class 应该只用于需要实例化对象的情况。否则效率低下(而且令人困惑)。对象字面量更简单。

标签: javascript typescript asynchronous async-await


【解决方案1】:

TypeScript 中的异步函数确实需要声明为返回 Promise,但您实际上并不需要从函数中返回 Promise。你可以只从异步函数返回承诺值的类型,它会被包装在一个承诺中。

因此,对于返回 Promise&lt;void&gt; 的异步函数,您可以只返回一个空的返回值或根本没有返回值。

class Item
{
}

class MyClass 
{

    public static async VoidAsyncWithReturn(): Promise<void>
    {
        return;
    }

    public static async VoidAsyncWithoutReturn(): Promise<void>
    {
    }

    private static async AsyncReturningValue(): Promise<Item[]> 
    {
        var result: Item[] = new Array();
        return result;
    }

    private static async AsyncReturningPromise(): Promise<Item[]> 
    {
        var result: Promise<Item[]> = new Promise<Item[]>(() => { return new Array() });
        return result;
    }
}

【讨论】:

  • 这在MyClass::getItems()Service::fetchData() 方法中都给了我错误The return type of an async function or method must be the global Promise&lt;T&gt; type
  • @Niek 抱歉,我搞混了。我已经更正了答案。
猜你喜欢
  • 2019-01-22
  • 1970-01-01
  • 2013-05-03
  • 2012-12-20
  • 2014-10-22
  • 1970-01-01
  • 2022-06-21
  • 1970-01-01
  • 2016-05-27
相关资源
最近更新 更多