簡體   English   中英

如何用 Javascript 中的異步請求的結果填充對象的屬性?

[英]How to fill a property of an object with the result of an async request in Javascript?

我有一個名為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 中的異步編程,我希望我能解釋一下。 提前謝謝了。

正如Heretic Monkey已經提到的那樣,這是行不通的(您只是無法同步訪問異步調用的結果: 如何從異步調用返回響應? )。
您可能應該使用虛擬值對其進行初始化,然后使用另一個函數設置該屬性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM