2016-08-19 109 views
1

打字稿類中的一個函數返回Promise<string>。如何解包/產生承諾內的價值。在Promise Typescript中獲取一個值

functionA(): Promise<string> { 
    // api call returns Promise<string> 
} 

functionB(): string { 
    return this.functionA() // how to unwrap the value inside this promise 
} 
+1

不能直接獲取值了承諾。您可以使用promise上的'.then()'處理程序來訪問該值。 – jfriend00

+0

這根本不可能,你不能在你交付之前買的東西玩,即使你有送貨通知,也不行。或者商店裏的人向你保證包裝正在上路。承諾管理時間,你想要的字符串根本就不存在,除了'then()',沒有辦法告訴它什麼時候會出現。 'functionB()'必須返回一個Promise,這是沒有辦法的。 – Thomas

回答

3

試試這個

functionB(): string { 
    return this.functionA().then(value => ...); 
} 
+0

仍然會返回'Promise ' – Rjk

+0

@Rjk在'then'函數中,'value'是'string' –

+0

是的,我明白這一點。我需要返回'string',而不是'Promise '。 – Rjk