【问题标题】:How to loop dynamically over multiple promises in a for loop while using fetch?使用fetch时如何在for循环中动态循环多个promise?
【发布时间】:2018-07-03 01:07:06
【问题描述】:

这是有效的:

    const limit = 1000
    // fetchMyProducts(page, limit, flag)
    return fetchMyProducts(1, 1, true)
    .then(function (products) {
        return fetchMyProducts(2, limit, false)
    }).then(function (totalProducts) {
        return fetchMyProducts(3, limit, false)
    }).then(function (totalProducts) {
        return fetchMyProducts(4, limit, false)
    }).then(function (totalProducts) {
        return fetchMyProducts(5, limit, false)
    }).then(function (totalProducts) {
        return fetchMyProducts(6, limit, false)
    }).then(function (totalProducts) {
        return fetchMyProducts(7, limit, false)
    })

我正在尝试通过 fetch 获取我们系统中的所有产品。 问题是,目前我知道有多少产品,但在 1 年 / 3 年内......谁知道??

我正在尝试动态循环获取并获取所有产品。

我已经尝试过了,但它似乎根本没有被调用。

    return fetchMyProducts(1, 1, true)
    .then(function (numberOfProducts) {
        let pages = Math.ceil(numberOfProducts / 1000) + 1;
        console.log(pages);
        return getAllProducts = () => {
            for (let i = 1; i < pages; i++) {
                const element = array[i];
                return fetchMyProducts(2, limit, false)

            }
        }
    }).then(... something else)

有没有办法循环一个 fetch promise 并在它完成时返回一些东西,然后继续做其他事情?

【问题讨论】:

  • 一个人不在 for 循环中 return 并期望所述循环继续
  • 我不明白,如果您想获得所有产品,为什么不只是创建一个 api 并调用它?为什么要提出很多要求才能获得所有产品?

标签: javascript node.js for-loop ecmascript-6 fetch-api


【解决方案1】:

你正在寻找

const limit = 1000
let chain = Promise.resolve();
for (let i=1; i<8; i++) {
    chain = chain.then(function(products) {
        return fetchMyProducts(i, limit, false)
    });
}
return chain;

它会动态构建您所阐明的承诺链。


如需更简单高效的解决方案,请考虑使用async/await

const limit = 1000
for (let i=1; i<8; i++) {
    const products = await fetchMyProducts(i, limit, false);
}
return;

【讨论】:

  • 第一个第一次完美运行!你是一个传奇。非常感谢。
猜你喜欢
  • 2020-07-27
  • 1970-01-01
  • 2019-01-07
  • 2016-12-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-31
  • 2018-01-03
相关资源
最近更新 更多