【问题标题】:Issues with fetch抓取问题
【发布时间】: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


【解决方案1】:

正如@Aniket 和@Linda Paiste 所提到的,添加 await 似乎对我有用。见例子:

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 = await initialRequest();
    console.log(data);
}
<button id="button">Button</button>

【讨论】:

    猜你喜欢
    • 2018-11-17
    • 1970-01-01
    • 1970-01-01
    • 2021-07-25
    • 2020-07-03
    • 2015-07-10
    • 2017-10-15
    • 1970-01-01
    相关资源
    最近更新 更多