AlexLuo
AlexLuo

Reputation: 487

TypeScript how to export const in a promise

What I want to implement is that get a data from the database, which the getter method is async, then export a const variable based on the promise returned value.

The code is like this:

import {Storage} from "@ionic/storage";
//...
storage.get("setup_done").then((val)=>{
  export const FirstRunPage = val?'valueA':'valueB';
}) 

However, I get an error message that:

Modifiers cannot appear here

enter image description here why could that happen?

Upvotes: 5

Views: 12498

Answers (1)

CRice
CRice

Reputation: 32186

All exports have to appear at the top level, and there's not really a way to do some kind of asynchronous export like you want.

The way I see it you have two options. The first, and probably the simplest, is to just export the promise itself:

import {Storage} from "@ionic/storage";
//...
export const FirstRunPagePromise = storage.get("setup_done").then((val)=>{
  return val ? 'valueA' : 'valueB';
})

That means that consumers of the module will have to access the value using .then, just like with any other promise.

Your second option is to assign the value to a variable when it resolves, and export a getter function for that variable:

import {Storage} from "@ionic/storage";
//...
let FirstRunPage: string;

storage.get("setup_done").then((val)=>{
  FirstRunPage = val ? 'valueA' : 'valueB';
});

export function getFirstRunPage() {
  return FirstRunPage;
}

You have to use the getter because importing the variable itself will give you a copy, which won't update when the promise resolves.

This approach means you can access the value synchronously, but if you access it too early, it will be undefined. So all your code would have to check to see if the value exists first, then use it. That or you have to know as the developer that whatever code accesses the value will only be running after the promise has been resolved.

Personally I recommend option 1, but I've done both before and ultimately it depends on your use case. Do what makes sense for your situation.

Upvotes: 6

Related Questions