Vue3使用Fetch API无法获取可用数据,仅得到已完成Promise
问题解决方法
你的问题出在两个核心点上:
- async 函数本身会返回 Promise,直接执行
console.log(getAllPhotos())打印的就是这个Promise对象,而非请求到的实际数据; - 你的
getAllPhotos函数里,虽然用await等待了请求结果,但没有返回这个结果,导致Promise最终resolve的值是undefined。
修复步骤:
首先修改函数,确保返回请求到的数据:
const getAllPhotos = async () => { // 简化写法,去掉多余的then链式调用,直接await后返回json结果 const response = await fetch("https://jsonplaceholder.typicode.com/photos"); return response.json(); };
然后通过以下两种方式获取并打印数据:
方式1:用.then处理Promise
getAllPhotos().then(photos => { console.log(photos); });
方式2:在async环境中用await
因为await只能在async函数内部使用,所以可以用立即执行的async函数包裹:
(async () => { const photos = await getAllPhotos(); console.log(photos); })();
这样就能正常打印出请求到的照片数据了。
内容的提问来源于stack exchange,提问作者juzello
相关产品推荐
相关产品推荐

