gpt4 book ai didi

javascript - 我应该使用 fetch() 和 .then 还是 async/await

转载 作者:行者123 更新时间:2023-12-04 08:26:40 27 4
gpt4 key购买 nike

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





Difference of using async / await vs promises?

(5 个回答)


9 个月前关闭。




以下代码段给了我相同的结果。 .then的用法有什么区别和 async/await获取数据?

// Code 1

function fetchData() {
fetch(url)
.then(response => response.json())
.then(json => console.log(json))
}



// Code 2

async function fetchData() {
const response = await fetch(url);
const json = await response.json();
console.log(json);
}

最佳答案

Async 和 await 只是语法糖。它们与“then”做同样的事情,但通常认为 await 语法更可取,因为它允许避免嵌套 then 语句并且可以说更容易阅读。

关于javascript - 我应该使用 fetch() 和 .then 还是 async/await,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65224967/

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