You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue3使用Fetch API无法获取可用数据,仅得到已完成Promise

问题解决方法

你的问题出在两个核心点上:

  1. async 函数本身会返回 Promise,直接执行console.log(getAllPhotos())打印的就是这个Promise对象,而非请求到的实际数据;
  2. 你的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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 08:20:42