使用获取时如何在for循环中动态遍历多个Promise? [英] How to loop dynamically over multiple promises in a for loop while using fetch?

查看:481
本文介绍了使用获取时如何在for循环中动态遍历多个Promise?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是有效的方法

    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)
    })

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

I am trying to get all the products in our system through fetch. The problem is, at the moment, I know how many products there are, but in 1 year / 3 years... who know??

I我试图尝试动态地循环获取并获取所有产品。

I am trying to loop over a fetch dynamically and get all the products.

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

I have tried this, however it doesn't seem to get called at all.

    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)

有没有一种方法可以遍历获取承诺并在获取承诺时返回某些内容完成,然后继续执行其他操作?

Is there a way to loop over a fetch promise and return something when it's finished, then continue on doing something else?

推荐答案

您在寻找

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;

这会动态构建您拼出的承诺链。

which dynamically builds the promise chain that you spelled out.

要获得更简单有效的解决方案,请考虑使用 async / await

For a more simple and efficient solution, consider using async/await:

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

这篇关于使用获取时如何在for循环中动态遍历多个Promise?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆