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

如何基于数组元素数量循环调用API函数?(TypeScript)

解决方案:循环调用API添加检查项

你的问题在于当前代码是把整个检查项数组一次性传给了createCheckitemOnChecklist函数,但根据需求需要遍历数组中的每个元素,单独调用API函数。下面是修改后的代码:

修正后的代码

let checkListID = "64db1d589d4a24da89794eb5";
// 修正数组类型定义,正确声明字符串数组
let checkItemsArray: string[] = [
  "And this is a item i would like to add", 
  "And this is another one#", 
  "And this is the final one"
];

// 循环调用API添加每个检查项
try {
  // 顺序执行每个API请求(适合需要按顺序添加的场景)
  for (const itemName of checkItemsArray) {
    await createCheckitemOnChecklist(flowElement, baseURL, key, token, checkListID, itemName);
  }

  // 如果允许并发执行(效率更高,API支持的话),可以用Promise.all:
  // await Promise.all(
  //   checkItemsArray.map(itemName => 
  //     createCheckitemOnChecklist(flowElement, baseURL, key, token, checkListID, itemName)
  //   )
  // );
} catch (error: any) {
  const axiosError = error as AxiosError;
  const axiosMessage = axiosError.response?.data?.message || "未知错误";
  const axiosStatus = axiosError.response?.status || 500;
  
  await flowElement.log(LogLevel.Error, `Trello API - 错误 ${axiosStatus} - ${axiosMessage}`);
  await job.sendToData(Connection.Level.Error);
  return;
}

关键修改点

  • 修正数组类型:原代码的数组类型声明错误,改为string[]明确是字符串数组。
  • 遍历数组调用API:用for...of实现顺序调用,确保每个检查项添加完成后再执行下一个;如果API支持并发,用Promise.all可以同时发起所有请求,提升效率。
  • 优化错误处理:添加可选链?.避免response为undefined时的报错,同时用模板字符串让日志更简洁。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 15:27:36