【问题标题】:How to Properly return a Promise in TypeScript?如何在 TypeScript 中正确返回一个 Promise?
【发布时间】:2022-11-29 02:04:53
【问题描述】:

我有以下代码:

import {initConnection,IapIosSk2, setup} from "react-native-iap"

async nativeTest() : Promise<ProductStatus[]>{
 

        try { 
            let stat: Promise<ProductStatus[]> =  await (IapIosSk2).subscriptionStatus('sku')
            setup({storekitMode:'STOREKIT2_MODE'})
            initConnection()
            return await new Promise((resolve, reject) => {
                if (stat) {
                    for (let data in stat){
                        console.log(data)
                    }
                    resolve(stat);
                } else {
                reject(new Error('Failed'));
                }
            });
            }
            catch(e){
                console.log(e)
            }
        }

我正在使用 react-native-IAP 库,并在“stat”变量下收到以下错误:

Type 'ProductStatus[]' is missing the following properties from type 'Promise<ProductStatus[]>': then, catch, finally, [Symbol.toStringTag]

我假设这是我处理 Promise 的方式的错误?任何决议都会很棒,谢谢。

【问题讨论】:

标签: typescript react-native


【解决方案1】:
let stat: Promise<ProductStatus[]> =  await (IapIosSk2).subscriptionStatus('sku')

await 的全部要点在于,它将包含函数置于睡眠状态,直到承诺得到解决,然后评估为承诺的已解决值。

如果你想要一个承诺,不要使用await。 (不要这样做,该行之后的代码假定您没有承诺)。

如果您使用await,那么您可能应该期待ProductStatus[]而不是Promise&lt;ProductStatus[]&gt;

【讨论】:

    【解决方案2】:

    这里的变量类型不会是 Promise<ProductStatus[],因为你已经使用 await 完成了承诺。 所以变量stat类型应该是ProductStatus[],

    【讨论】:

      猜你喜欢
      • 2017-01-07
      • 2019-01-24
      • 1970-01-01
      • 2019-04-11
      • 2023-03-13
      • 2019-09-17
      • 2017-06-09
      • 2020-08-06
      • 1970-01-01
      相关资源
      最近更新 更多