![](/img/trans.png)
[英]Should I have and async/await on a method if there is an await at the point where it is called?
[英]async/await in a class method called “then”
我創建了一個具有“then”方法的類。 這個類與Promise類型無關; “then”方法有不同的目的,不會返回承諾。 我試圖在Typescript 2.1.4中編寫async / await函數,等待並返回此類的實例,但VS Code中的Typescript服務器給了我錯誤。 如果我將方法重命名為“then”以外的其他方法,則錯誤消失。
帶錯誤的示例代碼:
class MyClass {
then(): number {
// this method isn't related to Promise.then
return 2 + 2;
}
}
// three errors below go away when "then" is renamed
// [ts] An async function or method must have a valid awaitable return type.
async function my_async(): Promise<MyClass> {
let a: Promise<MyClass> = Promise.resolve(new MyClass());
// [ts] Operand for 'await' does not have a valid callable 'then' member.
let b: MyClass = await a;
// [ts] Return expression in async function does not have a valid callable 'then' member.
return b;
}
有人可以解釋為什么不允許使用具有自己的“then”方法的對象的promises,或者解決這個問題?
Promise被定義為具有名為.then
的方法的對象。 例如,它們沒有被定義為“由require('bluebird/promise')
返回的模塊”。
使這一點變得重要的部分原因是,當一個promise庫正在解析一個promise時,如果該結果是一個promise本身,那么它並不意味着在.then
調用中提供最終結果。 例如:
function myFn() {
// doPromise1 will eventually give us `1`.
return doPromise1().then(x => {
// doPromise2 will eventually give us `2`.
return doPromise2();
});
}
調用此函數和調用.then
對結果不會返回我的內部承諾doPromise2()
它將返回2
- 所以它將等到兩個promises完成,並給出最終值。
這是,如果我回來了不同的3
內then
。 它會看到結果不是承諾,並將其作為最終值提供。 然而,問題的關鍵在於它如何知道這不是一個承諾。 它沒有做類型檢查,就像if p instanceof Promise
因為在各種庫中有太多的Promise定義和polyfill,並且它們意味着一起工作。 相反,他們檢查一些通用的東西應該是這樣的: if (typeof p.then === 'function')
。
對於您的班級,該檢查將返回true
,這會使其認為您的值本身就是Promise。 它運行它,希望得到另一個promise對象,但得到一個數字並失敗。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.