2017-10-11 101 views
0

我寫了這個函數來從API獲取和緩存一些數據。從Promise預期函數返回對象

export class MyService { 
    static items: Array<Post> = null; 

    async getItems(): Promise<Array<Post>> { 
    if (MyService.items) { 
     return MyService.items; 
    } 
    else { 
     return this.doRequest();  
    } 
    } 

    private async doRequest: Promise<Array<Post>> { 
    // get items from API. 
    } 
} 

據我所知,我必須從getItems功能,像返回一個承諾:return Promise.resolve(MyService.items),爲什麼(以及如何)以上功能仍能正常工作 - 我從無極預期函數返回一個對象?

回答

2

任何以async關鍵字開頭的函數都會自動將其返回值包含在承諾中。沒有必要手動使用Promise.resolve()等,儘管這樣做也非常好。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

當異步函數被調用,它返回一個承諾。 當異步函數返回一個值時,Promise將用返回的值解析。當異步函數拋出異常或某個值時,Promise將被拋出的值拒絕。

強調我的。該過程由於使用關鍵字async聲明功能而自動發生。

此外,typescript意識到這一點,所以只要您返回的值符合Array<Category>,typecript就會滿足,因爲它知道它將自動包裝到Promise<Array<Category>>中。