【问题标题】:How to use API result as the property of the object?如何使用 API 结果作为对象的属性?
【发布时间】: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


【解决方案1】:

任何声明为async 的函数都应为awaited(或使用.then())以使用其解析值。

所以你也只需要await 你的getCountries 函数。

options: (await getCountries).map(x => x.name)

【讨论】:

  • 给出错误。 'await' expression is only allowed within an async function.ts(1308)
  • 是的。任何等待异步函数的函数也必须(逻辑上)是异步的。所以这个错误会告诉你这里需要知道的一切。
  • 顶级await还在proposal阶段,不是吗?从使用export 来看,这显然处于顶层,使得export 异步所依赖的变量之一似乎有问题。根据另一个答案@MaheerAli,您必须导入并解决以这种方式做事的承诺
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多