首页 > 解决方案 > 类型 'boolean' 不可分配给类型 'Promise'

问题描述

我正在使用 inApp 购买,如果由于某种原因我无法从 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);
    });
  }

  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;
  }

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

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

有一个更好的方法吗?

任何帮助,将不胜感激。

标签: javascripttypescriptasync-awaitpromisein-app-purchase

解决方案


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

async setupProducts(): Promise<boolean> {
...
return false;
}

请注意,true值 fromthis.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;
}

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


推荐阅读