【发布时间】: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