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

JS调用带next_token的分页API收集total_tweet_count代码异常如何解决

问题分析
  • 变量未更新:你定义的results变量仅在首次请求时赋值,循环内请求的下一页结果存在临时变量results1中,没有同步更新到外层的results,导致每次循环都只会用第一次请求返回的next_token去请求数据,永远拿不到后续的token更新。
  • 循环判断逻辑异常:do-while的终止判断用的是上一次请求的next_token,没有校验最新请求返回的结果是否还有下一页,会导致无next_token时还会多执行一次请求报错。
修正后代码
const getData = async () => {
  const totalCount = [];
  // 存储每次请求的返回结果
  let currentResult = await Promise.resolve(data.res1);
  totalCount.push(currentResult.meta.total_tweet_count);
  // 只要当前结果存在next_token就继续请求下一页
  while (currentResult.meta.next_token) {
    currentResult = await Promise.resolve(data[`res${currentResult.meta.next_token}`]);
    totalCount.push(currentResult.meta.total_tweet_count);
  }
  return totalCount;
}

getData().then(res => console.log(res)) // 输出 [1, 20, 8]
逻辑说明
  • 用currentResult变量存储每次请求的返回结果,每次请求完直接更新该变量,确保每次取的next_token都是最新返回的有效值
  • 把do-while改为普通while循环,每次循环前先判断当前结果是否有下一页token,避免无token时发起无效请求报错
  • 执行流程:首次请求res1推入1→判断存在next_token=2→请求res2推入20→判断存在next_token=3→请求res3推入8→判断res3无next_token→终止循环返回数组

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 18:27:08