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

使用Fetch在JavaScript中链式POST请求时遇map函数报错问题

问题描述

我想要执行POST请求,获取作为主键返回的ID,再通过另一个API用这些ID填充不同的数据表。参考相关技术文章后始终遇到相同错误。

代码实现

async function handleAdd () {
  const shiftTypes = await fetch('myURL/shift-type', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    // 发送单个ShiftType对象(来自React状态)
    // 示例:{ "abbreviation": "ld", "description": "long day", "start": "12:54:00", "end": "22:54:00"}
    body: JSON.stringify(newShiftType),
  })
    .then(response => response.json());
  // 原文章代码是this.shiftType = shiftType
  let shiftTypesTwo = shiftTypes;
  const shiftTypeIds = shiftTypesTwo.map(shiftType => shiftType.shift_type_id);

  // 想要在另一个表创建28条记录,传入shift_type_id作为外键
  for (let i = 1; i <= 28; i++) {
    const shifts = await fetch('myURL/shift', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        people_required: 42,
        shift_type_id: shiftTypeIds[0],
      }),
    });
    console.log(shifts);
  }
}

报错信息

ShiftTypes.js:38 Uncaught (in promise) TypeError: shiftTypesTwo.map is not a function
    at handleAdd (ShiftTypes.js:38:1)
handleAdd   @   ShiftTypes.js:38
await in handleAdd (async)      
callCallback    @   react-dom.development.js:4164
invokeGuardedCallbackDev    @   react-dom.development.js:4213
invokeGuardedCallback   @   react-dom.development.js:4277
invokeGuardedCallbackAndCatchFirstError @   react-dom.development.js:4291
executeDispatch @   react-dom.development.js:9041
processDispatchQueueItemsInOrder    @   react-dom.development.js:9073
processDispatchQueue    @   react-dom.development.js:9086
dispatchEventsForPlugins    @   react-dom.development.js:9097
(anonymous) @   react-dom.development.js:9288
batchedUpdates$1    @   react-dom.development.js:26140
batchedUpdates  @   react-dom.development.js:3991
dispatchEventForPluginEventSystem   @   react-dom.development.js:9287
dispatchEventWithEnableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay @   react-dom.development.js:6465
dispatchEvent   @   react-dom.development.js:6457
dispatchDiscreteEvent

第38行对应代码:

const shiftTypeIds = shiftTypesTwo.map(shiftType => shiftType.shift_type_id);

问题原因与修复方案

原因分析

你发起的POST请求myURL/shift-type返回的是单个ShiftType对象(不是数组),而map是数组专属方法,直接对单个对象调用map就会抛出map is not a function错误。从代码注释的请求体示例也能看出,你发送的是单个对象,后端返回的自然是创建成功后的单条数据,而非数组。

修复代码

直接从返回的单个对象中提取shift_type_id即可,不需要用map:

async function handleAdd () {
  // 发起POST请求创建单个ShiftType
  const shiftType = await fetch('myURL/shift-type', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(newShiftType),
  })
    .then(response => response.json());

  // 直接提取单个shift_type_id
  const shiftTypeId = shiftType.shift_type_id;

  // 批量创建28条Shift记录
  for (let i = 1; i <= 28; i++) {
    const response = await fetch('myURL/shift', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        people_required: 42,
        shift_type_id: shiftTypeId,
      }),
    });
    // 解析响应查看创建结果(可选)
    const shift = await response.json();
    console.log(`创建第${i}条Shift记录:`, shift);
  }
}

额外优化建议

  • 如果后续需要同时创建多个ShiftType,需确保请求体是数组格式,且后端返回创建后的数组列表,此时再用map提取ID才合理。
  • 批量创建请求可以用Promise.all并行发起,提升效率(注意确认后端是否支持高并发):
// 并行创建28条记录
const createShiftPromises = Array.from({ length: 28 }, () => 
  fetch('myURL/shift', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      people_required: 42,
      shift_type_id: shiftTypeId,
    }),
  }).then(res => res.json())
);

const createdShifts = await Promise.all(createShiftPromises);
console.log('所有Shift记录创建完成:', createdShifts);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 02:40:40