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

如何从API调用中返回JSON格式结果?

问题描述

我编写了一个JavaScript异步函数,用于调用拼写检查API:

async function checkWord(word) {
  var myHeaders = new Headers();
  myHeaders.append("apikey", "My api key");
  var requestOptions = {
    method: 'GET',
    redirect: 'follow',
    headers: myHeaders
  };
  fetch(`https://api.apilayer.com/spell/spellchecker?q=${word}`, requestOptions)
  .then(response => response.text())
  .then(result => console.log(result))
  .catch(error => console.log('error', error));
}

待检查的单个单词以字符串参数传入,示例调用:

let checkResult = checkWord('HOUSE');
console.log(checkResult);

我想改写这一行代码,让函数把结果以JSON对象形式返回给调用者:

.then(result => console.log(result))

尝试的写法是:

.then(result => () => {return result.json();})

原代码能正常运行,console.log(result)可以显示有效结果,但调用函数后的console.log(checkResult)只显示Promise相关内容。

修复方案

要实现需求,需要两处关键修改:

  1. 让函数返回Promise链:原函数没有返回fetch发起的异步操作,所以调用后得到的是默认包装undefined的Promise。必须在fetch前添加return,让函数返回整个异步流程的Promise。
  2. 正确解析并返回JSON:原代码用response.text()把响应转为文本,要得到JSON对象应该直接用response.json(),并且在then中直接返回解析后的结果,而非返回一个函数。

修改后的完整代码:

async function checkWord(word) {
  var myHeaders = new Headers();
  myHeaders.append("apikey", "My api key");
  var requestOptions = {
    method: 'GET',
    redirect: 'follow',
    headers: myHeaders
  };
  // 返回整个Promise链
  return fetch(`https://api.apilayer.com/spell/spellchecker?q=${word}`, requestOptions)
  .then(response => response.json()) // 直接解析响应为JSON
  .then(result => {
    console.log(result); // 可选:保留日志用于调试
    return result; // 将JSON对象返回给调用者
  })
  .catch(error => {
    console.log('error', error);
    throw error; // 抛出错误,让调用者可以捕获处理
  });
}

调用时,因为是异步操作,需要用await或.then()获取结果:

// 方式1:在async函数中使用await
async function getSpellResult() {
  let checkResult = await checkWord('HOUSE');
  console.log(checkResult);
}
getSpellResult();

// 方式2:使用Promise的then方法
checkWord('HOUSE').then(checkResult => {
  console.log(checkResult);
});

错误原因说明

  • 原函数未返回fetch的Promise,导致调用checkWord得到的是已决议为undefined的Promise。
  • 你尝试的写法返回了一个函数,而非解析后的JSON对象,不符合Promise链的处理逻辑——then回调需要返回值或Promise,而不是函数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 06:52:56