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

调用双API结合map生成嵌套数组时children为Promise<fulfilled>如何解决

问题原因说明

关于fulfilled的含义

Promise 共有三个状态:

  • pending:执行中,尚未得到结果
  • fulfilled:已成功执行完成,存在可读取的返回结果
  • rejected:执行失败,抛出错误
    你打印看到的Promise {<fulfilled>: Array(11)}意思是这个Promise已经执行成功,结果是长度为11的数组,但你没有把结果从Promise里取出来,而是直接把Promise对象赋值给了children字段,所以无法直接读取children的内容。

你的代码不生效的原因

你虽然用了Promise.all,但传进去的数组元素是普通的对象,不是Promise实例。你的逻辑是拿到分类列表之后,直接在map里同步返回了带Promise类型children的对象,Promise.all只会等待传入的Promise类型元素执行完成,普通对象会直接返回,所以根本没等children的请求结束就返回了结果,自然拿不到正确的children数组。

修正方案

你需要把每个分类的处理逻辑改成先等children的请求返回,再组装成完整的对象,再把这些Promise实例传给Promise.all即可。

async/await 写法(可读性更高)

async function getCategories() {
  const catRes = await fetch('https://challenge.fnaghshin.com/api/cat')
  const categories = await catRes.json()
  // 每个分类对应一个Promise,等子项请求完成后再组装对象
  const result = await Promise.all(
    categories.map(async (e) => {
      // 先请求当前分类的子项
      const childRes = await fetch(`https://challenge.fnaghshin.com/api/catpro/${e.id}`)
      const children = await childRes.json()
      const formattedChildren = children.map(item => ({
        key: item.id,
        label: item.name
      }))
      // 子项处理完成后再返回完整对象
      return {
        key: e.id,
        label: e.name,
        date: e.created_at,
        children: formattedChildren
      }
    })
  )
  return result
}

保留原then链的写法

getCategories() {
  return fetch('https://challenge.fnaghshin.com/api/cat')
    .then((res) => res.json())
    .then((d) => {
      return Promise.all(
        d.map((e) => {
          // 这里返回的是Promise,等子请求完成后再组装对象
          return fetch(`https://challenge.fnaghshin.com/api/catpro/${e.id}`)
            .then((res) => res.json())
            .then((children) => {
              const formattedChildren = children.map(item => ({
                key: item.id,
                label: item.name
              }))
              return {
                key: e.id,
                label: e.name,
                date: e.created_at,
                children: formattedChildren
              }
            })
        })
      );
    });
}

调用注意事项

不管用哪种写法,getCategories本身返回的是一个Promise,你调用的时候需要用await或者.then来拿最终的结果:

// 调用示例
getCategories().then(res => {
  console.log(res) // 这里拿到的就是符合你要求格式的数组
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 20:18:03