类型“boolean”不可分配给类型“Promise<boolean>”

D.H*_*ges 8 javascript in-app-purchase promise async-await typescript

我正在使用应用内购买,如果由于某种原因我无法从 Google 或 iOS 应用商店检索产品信息,我想将 UI 更改为“不可用”。

  ionViewDidEnter() {
    this.platform.ready().then(async () => {
      firebase.auth().onAuthStateChanged(async user => {
        this.currentUser = user;
      });
      this.unavailable = await this.setupProducts();
      console.log('available', this.unavailable);
    });
  }
Run Code Online (Sandbox Code Playgroud)

  setupProducts(): Promise<boolean> {
    let productWWHS: string;
    let productISA: string;

    if (this.platform.is('ios')) {
      productWWHS = 'prodID';
      productISA = 'prodID';

    } else if (this.platform.is('android')) {
      productWWHS = 'prodID';
      productISA = 'prodID';
    }

    this.inAppPurchase.ready(() => {
      this.products.push(this.inAppPurchase.get(productWWHS));
      this.products.push(this.inAppPurchase.get(productISA));
      if (!this.products[0]) {
        return true;
      }
    });
    return false;
  }
Run Code Online (Sandbox Code Playgroud)

我在这个方法中做错了,它有错误类型“boolean”不能分配给类型“Promise”

我想以某种方式断言 inAppPurchase.get() 已经返回了一些东西,但它没有返回承诺。

有一个更好的方法吗?

任何帮助,将不胜感激。

小智 9

要修复键入错误,您需要将函数定义为async

async setupProducts(): Promise<boolean> {
...
return false;
}
Run Code Online (Sandbox Code Playgroud)

请注意,truefrom 的值this.inAppPurchase.ready(() => {...})不会从 中返回setupProducts()。它将从匿名函数返回() => {...},不会影响任何内容。

你可能需要类似的东西

async setupProducts(): Promise<boolean> {
...
await this.inAppPurchase;

this.products.push(this.inAppPurchase.get(productWWHS));
this.products.push(this.inAppPurchase.get(productISA));

if (!this.products[0]) {
  return true;
}

return false;
}
Run Code Online (Sandbox Code Playgroud)

不要忘记()ifthis.inAppPurchase是一个函数而不是 getter。