我正在尝试弄清楚如何将获取的输出保存到变量中。我的目标是将其用作对象。
这是我的代码:
async function getWeather() {
let response = await fetch('url');
let result = await response.json();
return console.log(result);
}
getWeather();
该代码给了我预期的响应
我尝试返回结果而不是控制台日志并将其存储在变量( let weather=getWeather();
)中,这给了我 promise 对象
当我控制台登录时weather
.
我还尝试了这个问题的另一种解决方案,已得到解答 here ,但是当我尝试在获取之外控制台记录对象时,我会得到未定义的结果。
还有其他解决办法吗?
最佳答案
您已将其定义为 async
函数,它始终会首先返回一个 Promise
。
在 console.log()
调用中使用 await
关键字来 await
获取返回值。
async function getWeather() {
let response = await fetch('https://api.weather.gov/alerts');
let result = await response.json();
return result;
}
(async () => {
document.querySelector("#output").innerText = JSON.stringify(await getWeather(), null, 2);
})();
<pre id="output"></pre>
关于JavaScript Fetch API - 将输出保存为对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61536110/