简体   繁体   English

TypeScript如何在Promise中导出const

[英]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. 我要实现的是从getter方法异步的数据库中获取数据,然后根据promise返回值导出const变量。

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

在此处输入图片说明 why could that happen? 为什么会发生这种情况?

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: 第一个,可能也是最简单的,是仅导出promise:

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. 这意味着模块的使用者将必须使用.then来访问值,就像其他承诺一样。

Your second option is to assign the value to a variable when it resolves, and export a getter function for that variable: 第二种选择是在解析时将值分配给变量,并为该变量导出getter函数:

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 . 您必须使用getter,因为导入变量本身将为您提供一个副本,当promise解决后,该副本将不会更新

This approach means you can access the value synchronously, but if you access it too early, it will be undefined . 这种方法意味着您可以同步访问该值, 但是如果过早访问它,它将是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. 我个人建议使用选项1,但我之前做过,最终取决于您的用例。 Do what makes sense for your situation. 做对您的情况有意义的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM