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

Promise结果无法使用问题求助:代码未按预期运行

嘿,这个问题其实是对Promise的异步特性理解不到位导致的,我来给你拆解一下~

问题根源

你在第二个fetch的请求体里写的b.then((customerIds) => customerIds),返回的仍然是一个Promise对象,而不是你想要的数组。因为Promise是异步的,当你执行JSON.stringify的时候,这个Promise还处于pending状态,JSON无法正确序列化Promise,所以后端收到的ids会是一个空对象{}或者不符合预期的内容,自然就失效了。

直接在变量b后面调用b.then(...)能拿到数组,是因为then的回调会在Promise resolve之后执行,这时才能拿到实际的数组值,但你把then的结果直接塞进请求体,本质上还是把Promise传进去了,不是数组本身。

解决方案

有两种清晰的写法可以解决这个问题,选你觉得顺手的就行:

方案1:用async/await(更直观,适合新手)

这种写法把异步代码写成类似同步的样子,逻辑一目了然:

async function getUsersFromOrders() {
  // 先拿到订单数据
  const rawOrders = await fetch('/orders');
  const orders = await rawOrders.json();
  
  // 提取customerIds,用map比forEach+push更简洁
  const customerIds = orders.map(order => order.customer);
  
  // 拿到数组后,再发送第二个请求
  const rawUsers = await fetch('/users', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({ ids: customerIds })
  });
  
  const users = await rawUsers.json();
  console.log('users', users);
}

// 调用这个异步函数
getUsersFromOrders();

方案2:用Promise链式调用(传统异步写法)

把第二个fetch放在第一个Promise的then回调里,确保只有拿到customerIds之后才发送请求:

fetch('/orders')
  .then(rawOrders => rawOrders.json())
  // 一步提取customerIds
  .then(orders => orders.map(order => order.customer))
  // 拿到数组后再发请求
  .then(customerIds => {
    return fetch('/users', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ ids: customerIds })
    });
  })
  .then(rawUsers => rawUsers.json())
  .then(users => console.log('users', users))
  // 别忘了加错误处理,避免异步请求出错时没有提示
  .catch(error => console.error('请求过程出错:', error));

额外小建议

  • 用Array.map替代forEach+push来生成数组,代码更简洁高效,也更符合JavaScript的函数式编程风格。
  • 异步操作一定要加错误处理(比如catch或者try/catch),不然请求失败的时候你根本不知道哪里出了问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 09:52:56