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

如何用Fetch API编写返回JSON的函数?含await与.then实现

问题分析与解决方案

失败原因

你之前的写法无法返回JSON的核心原因是:Fetch API 是异步操作,返回的是 Promise 对象,不能直接同步获取异步操作的结果。如果只是在函数内部赋值后返回,实际上返回的是一个还处于 pending 状态的 Promise,而非最终解析完成的 JSON 数据。

正确实现

1. async/await 写法(getJson1)

async function getJson1(url) {
  try {
    const response = await fetch(url);
    if (!response.ok) {
      throw new Error(`请求失败: ${response.status}`);
    }
    const jsonData = await response.json();
    return jsonData; // 这里返回的是被Promise包裹的jsonData,调用时需用await或.then获取
  } catch (error) {
    console.error('获取JSON出错:', error);
    throw error; // 抛出错误让调用方处理
  }
}

2. .then 链式调用写法(getJson2)

function getJson2(url) {
  return fetch(url)
    .then(response => {
      if (!response.ok) {
        throw new Error(`请求失败: ${response.status}`);
      }
      return response.json();
    })
    .catch(error => {
      console.error('获取JSON出错:', error);
      throw error;
    });
}

调用示例

不管用哪种写法,调用时都需要处理异步结果:

// 调用getJson1
async function useGetJson1() {
  try {
    const data = await getJson1('https://example.com/api/data');
    console.log(data); // 这里才能拿到最终的JSON数据
  } catch (err) {
    // 处理错误逻辑
  }
}

// 调用getJson2
getJson2('https://example.com/api/data')
  .then(data => console.log(data))
  .catch(err => { /* 处理错误逻辑 */ });

可选API推荐

如果你正在学习Promise,除了Fetch API,还可以了解:

  • axios:基于Promise的HTTP客户端,封装更完善,自带JSON解析、拦截器等功能,使用更简洁
  • Node.js环境下的node-fetch:和浏览器Fetch API一致,适合Node.js端发起请求
  • 原生XMLHttpRequest:虽然是回调式,但能帮助理解异步底层逻辑(不过现在更推荐Promise方案)

内容的提问来源于stack exchange,提问作者komote7665

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 17:35:30