【问题标题】:How to use promises with recursive fetch?如何使用带有递归获取的承诺?
【发布时间】:2018-12-22 06:03:38
【问题描述】:

我正在使用 fetch 检索一棵树,一次一层。获取所有分支后如何触发操作?树有多个分支,我不知道提前的深度。

伪代码:

until Children is empty fetchChildren()

after all children are retrieved doSomething()

我找到了一些答案,但它们只处理链式 then(),而不是树。

[edit] 虽然不是强制性的,但我希望该解决方案可以在 IE11 中运行。我已经在使用 promise 并获取 polyfill。

【问题讨论】:

  • Promise.all() 每一层?
  • 这适用于单层,但 doSomething 应该仅在获取所有层和子层后运行。而且我事先不知道有多少。所以基本上我正在寻找一个递归的 Promise.all()。

标签: javascript recursion promise fetch


【解决方案1】:

这是一种使用递归异步函数执行此操作的方法,该函数等待完成元素的子元素的获取,然后返回一个承诺。

这样,我们可以在一切完成后致电doSomething

const tree = {
  url: 'http://www.json-generator.com/api/json/get/cevhxOsZnS',
  children: [{
    url: 'http://www.json-generator.com/api/json/get/cguaPsRxAi'
  }, {
    url: 'http://www.json-generator.com/api/json/get/cguaPsRxAi',
    children: [{
      url: 'http://www.json-generator.com/api/json/get/cfDZdmxnDm'
    }]
  }]
};

function doSomething() {
  console.log("doing something");
}

async function fetchIt(element) {
  if (element.children) {
    await Promise.all(element.children.map(fetchIt));
  }
  return new Promise((resolve) => {
    console.log("fetching " + element.url);
    fetch(element.url).then(res => {
      console.log("done");
      resolve();
    });
  });
}

fetchIt(tree).then(doSomething);

【讨论】:

  • 这太复杂了。
  • @Christophe 我承认生成器方法有点复杂,并且无论如何都不涉及递归获取。我编辑了我的答案。
【解决方案2】:

只需首先等待获取层元素,然后递归处理子元素并等待:

async function fetchChildren(layer) {
  await Promise.all(layer.map(fetch));
  await Promise.all(layer.map(el => fetchChildren(el.children)));
}

(fetch(el) 必须是一个很有前途的功能)

【讨论】:

    猜你喜欢
    • 2015-12-05
    • 1970-01-01
    • 2017-05-09
    • 2014-02-04
    • 1970-01-01
    • 2016-06-10
    • 1970-01-01
    • 2016-12-02
    • 2016-12-23
    相关资源
    最近更新 更多