【问题标题】:recursively fetch all pages from api从 api 递归获取所有页面
【发布时间】:2021-12-26 12:48:13
【问题描述】:

我正在尝试从远程 api 获取所有记录,该远程 api 对一次可以获取的数量有限制。我正在尝试使用递归,但在 Python 中有效的一般概念我也无法在 JS 中工作。

这就是我目前正在做的事情,它将获取 100 条记录,然后在后台继续运行。我尝试了许多不同的方法来做到这一点,但似乎没有任何效果。

任何帮助都会很棒,谢谢。

  async getBooks(offset = 0) {
    return await bookGenie.find(
      'fiction',
      100,
      offset,
    )
  }

【问题讨论】:

  • 看起来 bookGenie.find 是异步的并返回 Promise 但您仍然使用回调来处理结果。也许它需要重写为仅承诺?可以提供bookGenie.find代码吗?
  • 我更新了代码,看起来它将返回一个包含最多 100 个对象的数组的承诺。我想一直坚持到最后。

标签: javascript api recursion async-await


【解决方案1】:

我推荐这个:

async function getBooks(offset = 0, result = []) {
  try {
    // get new page
    const page = await bookGenie.find(
      'fiction',
      100,
      offset,
    );
    // add page to result array
    result = result.concat(page);
    // check is this the end
    if (page.length !== 100) { // or what condition do you need
      // return result array
      return result;  
    } else {
      // or increase offset and continue processing
      return getBooks(offset + 100, result);
    }
  } catch (err) {
    throw err; // or handling somehow
  }
}

现在递归 getBook 返回承诺,所有发现的记录在解析时合并到一个数组中,并在拒绝时抛出错误。
所有请求将逐个执行,每一步增加偏移量 100,直到请求返回少于 100 条记录(不是整页 = 列表结尾)。

用法:

const list = await getBooks();
console.log(list); 
// [ ... ]
// List of all records

额外:相同的方法但紧凑

async function getBooks(offset = 0, result = []) {
  try {
    const page = await bookGenie.find('fiction', 100, offset);
    return page.length !== 100 ? result.concat(page) : getBooks(offset + 100, result.concat(page));
  } catch (err) {
    throw err; // or handling somehow
  }
}

【讨论】:

  • @ScottSauyet 哦,你是对的!感谢您的通知,我编辑了代码 sn-p。
【解决方案2】:

您的await getBooks() 电话:

getBooks((offset = offset += 100))

应该写成这样:

getBooks((offset += 100))

在我看来,之前的 if 语句是错误的。也许试试:

if (result.length < 1000) { // will continue until result.length is 1000
    result.push(await getBooks(offset += 1)); /* + 1 so the .push will add one element to the array each time. + 100 may work too */
}

我无法实际测试这个,但是这个(或类似的东西)对于 JS 来说更传统。这是一个可以帮助你的链接https://www.javascripttutorial.net/javascript-recursive-function/

【讨论】:

  • ` 偏移量 = 偏移量 + 100; ` 等同于 ` offset += 100; ` 在 JS 中,顺便说一句
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-11
  • 1970-01-01
  • 1970-01-01
  • 2016-08-25
  • 2013-08-13
相关资源
最近更新 更多