【发布时间】:2019-12-31 03:38:28
【问题描述】:
我正在使用 JavaScript 和 TypeScript 制作一个单页 Web 应用程序。我也在使用 JavaScript 的模块系统(type="module")。
我有一个名为Form 的类,它接收一个对象并创建一个Form。我有一个模块,其中包含注册表的所有数据。在具有选项字段的输入中有一个选择。我将那些选项分配给包含国家名称的数组。我正在使用 API 来获取国家/地区的名称。但我被困住了。
下面是我的文件RegisterFormDialog.ts
const RegisterFormData: IForm = {
//... Some other props
inputs: [
//..Some other objects.
{
name: "country",
type: "select",
label: "Country",
options: countries.map(x => x.name) // Here I want result of the api
}
]
};
export const RegisterForm = new Form(RegisterFormData);
export const RegisterFormDialog = new Dialog({
child: RegisterForm.element,
title: "Register",
dismissable: true,
onClose: () => 5,
parentElement: qs("#main") as HTMLElement
});
另一个文件是具有API功能的。它的名字是GetCountries.ts
export default async function getCountries() {
return await (await fetch("https://restcountries.eu/rest/v2/all")).json();
}
现在如何将 API 数据的返回值分配给对象中的 options 属性。
【问题讨论】:
-
目前尚不清楚您展示的任何内容如何组合在一起。
this.options = await getCountries(),也许吧?给minimal reproducible example。 -
@jonrsharpe 是的,这
this.options = await getCountries()我最接近我的需要。但问题是我不能在没有async的情况下使用await -
正确,因为它真的只是一个承诺,something需要解决它。
-
@jonrsharpe 那么这是否意味着如果我想要这里的这个 api 数据我将改变整个代码结构?
-
就是这样,是的。
标签: javascript typescript async-await