Home > database >  How to Properly return a Promise in TypeScript?
How to Properly return a Promise in TypeScript?

Time:11-29

I have the following code:

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

I am using react-native-IAP library, and am getting the following error under the "stat" variable:

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

I am assuming this is an error with how I'm dealing with the Promise? Any resolution would be great, thanks.

CodePudding user response:

let stat: Promise<ProductStatus[]> =  await (IapIosSk2).subscriptionStatus('sku')

The whole point of await is that it puts the containing function to sleep until the promise is resolved and then evaluates as the resolved value of the promise.

If you want a promise there, don't use await. (Don't do this, the code after that line assumes you don't have a promise).

If you use await then you should probably be expecting ProductStatus[] and not Promise<ProductStatus[]>.

CodePudding user response:

Here the variable will type will not be Promise<ProductStatus[], Because you have fullfill the promise using the await. So the variable stat type should be ProductStatus[],

  • Related