gpt4 book ai didi

javascript - 使用 fetch JS 进行异步/等待

转载 作者:行者123 更新时间:2023-12-05 00:31:09 30 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





How do I return the response from an asynchronous call?

(43 个答案)



How to access the value of a promise?

(13 个答案)


去年关闭。




我在创建一个将停止所有代码直到完成的函数时遇到问题。我想使异步/等待。在那个函数中我应该获取,但是当我返回结果时它说 promise {}
代码:

    const request = async (url) => {
const response = await fetch(url);
const json = await JSON.stringify(response.json());
return json;
}
let tree = request('humans.json');

console.log(tree);

最佳答案

异步函数可以通过两种方式调用。

  • 使用 then 方法
  • request.then(resp => console.log(resp)).catch(e => console.log(e));
  • 使用 await - 要使用 await 你需要一个异步函数,否则 await 关键字会出错并且只能在异步函数内部调用。
  • async function exe() {
    try {
    const result = await request(); // Now this will wait till it finished
    console.log(result);
    } catch(e) {
    console.log(e);
    }
    }

    关于javascript - 使用 fetch JS 进行异步/等待,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67955033/

    30 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com