【问题标题】:Type 'boolean' is not assignable to type 'Promise<boolean>'类型 'boolean' 不可分配给类型 'Promise<boolean>'
【发布时间】:2021-04-06 17:22:32
【问题描述】:

我正在使用应用内购买,如果由于某种原因我无法从 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() 已经返回了一些东西,但它没有返回一个承诺。

有没有更好的方法来做到这一点?

任何帮助将不胜感激。

【问题讨论】:

    标签: javascript typescript async-await promise in-app-purchase


    【解决方案1】:

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

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

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

    你可能需要类似的东西

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

    如果this.inAppPurchase 是函数而不是getter,请不要忘记()

    【讨论】:

    • 它是一个函数而不是一个 getter 是如何影响任何事情的?您是否建议它可能是异步操作,我需要等到它完成?顺便说一句,您的建议有效,但我想了解 .get 函数的含义。
    • @D.Hodges 如果它是这样声明的函数:async inAppPurchase(): Promise&lt;void&gt; 那么await this.inAppPurchase; 行将不会执行inAppPurchase。要执行它,您需要使用 () 调用它:await this.inAppPurchase();
    猜你喜欢
    • 2017-06-29
    • 2021-06-07
    • 1970-01-01
    • 2019-01-04
    • 2023-01-22
    • 2020-08-29
    • 2023-01-18
    • 2021-11-16
    • 1970-01-01
    相关资源
    最近更新 更多