【问题标题】:How to fill a property of an object with the result of an async request in Javascript?如何用 Javascript 中的异步请求的结果填充对象的属性?
【发布时间】:2021-09-11 23:29:36
【问题描述】:

我有一个名为 config 的对象,我将它导出到一个 ts 文件中。我需要用异步请求的结果填充 config.userServiceUrl
myconfig.ts:

export const config = {
   userServiceUrl: "shouldBeResultOfGetAsync",
   someProperty: "someValue"
}

我有一个名为 GetAsync 的函数

  export async function GetAsync(url: string) {
  let response = await fetch(url, {
     method: 'GET',
     headers: {  'Content-Type': 'application/json' },
     body: JSON.stringify(data) 
  });
  let json = await response.json();
  return json;
 }

如果我用一些虚拟值(例如空字符串)初始化 config.userServiceUrl,稍后我可以使用 .then() 方法设置该属性,如下所示:

GetAsync(myUrl).then((result) => { config.userServiceUrl = result; } )

但我需要用异步请求的结果初始化 userServiceUrl 属性。

我可以使用 await 关键字访问 GetAsync 方法的结果。但我不能这样设置:

export const config = {
       userServiceUrl: await GetAsync(myUrl),
       someProperty: "someValue"
    }

我还无法理解 JS 中的异步编程,希望我能解释一下。非常感谢。

【问题讨论】:

  • 你只是不能同步访问异步调用的结果。
  • 首先感谢您的回复。我明白我不能做什么,但我不确定如何正确设置该属性。
  • 对。这就是为什么我向您指出了一个问题,其中的答案显示了如何做到这一点。

标签: javascript async-await fetch es6-promise


【解决方案1】:

正如Heretic Monkey 已经提到的那样,这不起作用(您只是无法同步访问异步调用的结果:How to return the response from an asynchronous call?)。
您可能应该使用虚拟值对其进行初始化,然后使用另一个函数设置属性。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-03
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多