2

This is what works:

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

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 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?

waz
  • 1,165
  • 16
  • 31
  • 1
    one does not `return` in a for loop and expect said loop to continue – Jaromanda X Jan 24 '18 at 04:34
  • I don't understand, if you want to get all product why you don't just create an api and call it ? Why have to make a lot of request to get all product ? – DarknessZX Jan 24 '18 at 04:40

1 Answers1

8

You are looking for

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.


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;
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • That first one worked perfectly first time! You are a legend. Thank you so much. – waz Jan 24 '18 at 04:41