我对 async/await 的概念有点困惑,特别是当它与函数中的 .then() 相比时。
我目前正在使用一个基本的 React 应用程序,并在 useEffect 中获取一些数据
我想知道,由于 fetch 返回 Promise ,为什么在执行以下示例时我不需要将任何内容标记为 async 或 await :
useEffect(() => {
fetch("whatever").then(res => console.log(res));
}, [])
但是当我选择执行 await 时,我需要将代码包装在 async 函数中
useEffect(() => {
// error, needs to be in an async function
const res = await fetch("whatever");
},[])
我想我的问题实际上是使用 .then() 与使用 async await 链接之间有什么区别,为什么 .then() 不需要我等待任何东西,即使获取返回一个承诺?< /p>
谢谢
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
要添加到@HEllRZA,then() 和 async/await 都可以用来处理 JavaScript 中的 Promise。 then() 是一种采用回调函数作为参数的方法,并允许您链接多个 then() 方法来按顺序处理响应。 Async/await 是一种在 JavaScript 中编写异步代码的新方法。