【发布时间】:2021-07-16 08:51:28
【问题描述】:
const button = document.getElementById('button');
async function initialRequest() {
const data = await fetch("https://api.stackexchange.com/2.2/questions?page=1&pagesize=5&order=desc&sort=creation&site=stackoverflow")
.then((res) => res.json())
.then((data) => {return data.items});
return data;
}
button.onclick = async (e) => {
let questionCount = document.getElementById('limitVal');
const value = questionCount.value;
const data = initialRequest();
console.log(data);
}
当我尝试运行上述代码块时,我从该代码中得到一个网络错误,并且浏览器调试器指出 initialRequest 函数中的右括号是一个问题。但是,当我从事件回调内部发出请求时,它工作正常。问题是有更多的代码将进入这个项目,我想尽可能多地拆分。
【问题讨论】:
-
intialRequest() 正在恢复承诺
-
是的,你需要
await它。const data = await initialRequest(); -
如果您使用的是 async/await,为什么还要使用
then块?
标签: javascript async-await fetch-api