ReactFix
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • React
  • React Native
  • Programming
  • Object Oriented Programming

Tuesday, November 29, 2022

[FIXED] How to Properly return a Promise in TypeScript?

 November 29, 2022     react-native, typescript   

Issue

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.


Solution

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[]>.



Answered By - Quentin
Answer Checked By - - Marie Seifert (ReactFix Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Newer Post Older Post Home

Featured Post

Is Learning React Difficult?

React is difficult to learn, no ifs and buts. React isn't inherently difficult to learn. It's a framework that's different from ...

Total Pageviews

Copyright © ReactFix