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

使用Promise方法异步读取数组内书籍(禁止循环实现)

解决方案

因为要求禁止使用循环,我们可以通过递归调用实现按顺序读取书籍的逻辑,每次读完当前书籍拿到剩余时间后,再递归触发下一本书的读取,时间不足触发reject时自动终止流程。

你可以在index.js的注释位置补充如下代码:

// 递归读取书籍的函数
function readNext(remainingTime, bookIndex) {
  // 所有书籍读取完成直接终止流程
  if (bookIndex >= books.length) return
  readBooksPromise(remainingTime, books[bookIndex])
    .then(newRemainingTime => {
      // 当前书籍读取完成,递归调用读取下一本
      readNext(newRemainingTime, bookIndex + 1)
    })
    .catch(() => {
      // 剩余时间不足,直接终止读取
      return
    })
}

// 初始调用:初始时间10000ms,从下标为0的书籍开始读取
readNext(10000, 0)

运行后输出结果如下:

i start reading LOTR
i've finished reading LOTR, my time now 7000 left
i start reading Fidas
i've finished reading Fidas, my time now 5000 left
i start reading Calculus
i've finished reading Calculus, my time now 1000 left
i start reading comics
i've finished reading comics, my time now 0 left

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 02:12:01