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

如何不使用setTimeout将fetch获取的API数据传入自定义函数做后续处理

问题原因

你遇到返回值为undefined的核心原因是fetch是异步非阻塞API:代码执行到fetch调用时会直接向后执行后续逻辑,不会等待接口返回结果。此时你如果在fetch语句之后直接访问stored_data,.then里的数组赋值逻辑还没有触发,数组自然是空的。

解决方法

以下两种方案都不需要用到setTimeout,可以保证数据存入数组后再执行test函数:

方法1:在Promise链式回调中调用test

直接把test的执行逻辑放到最后一个.then回调内,确保数据存入数组后才触发执行:

let stored_data = []

fetch('https://jsonplaceholder.typicode.com/todos/1')
  .then(response => response.json())
  .then(json => {
    stored_data.push(json)
    // 数据存入完成后调用test
    test(stored_data)
  })

function test(e) {
  console.log(e)
}

方法2:使用async/await语法简化异步逻辑

async/await是Promise的语法糖,写法更贴近同步代码,可读性更高:

let stored_data = []

// 封装异步请求逻辑
async function fetchData() {
  const response = await fetch('https://jsonplaceholder.typicode.com/todos/1')
  const json = await response.json()
  stored_data.push(json)
  return stored_data
}

// 调用方式1:用.then接收返回结果
fetchData().then(data => test(data))

// 调用方式2:如果外层支持async上下文,也可以用await写法
// async function main() {
//   const data = await fetchData()
//   test(data)
// }
// main()

function test(e) {
  console.log(e)
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 17:54:03