7

so i have a promise that collects data from a server but only collects 50 responses at a time. i have 250 responses to collect.

i could just concate promises together like below

new Promise((resolve, reject) => {
    resolve(getResults.get())
    })
    .then((results) => {
    totalResults.concat(results)
    return getResults.get()
    })
    .then((results) => {
    totalResults.concat(results)
    return getResults.get()
    }).then((results) => {
     totalResults.concat(results)
    return getResults.get()
    })

In this instance i only need 250 results so this seems a managable solution but is there a way of concating promises in a loop. so i run a loop 5 times and each time run the next promise.

Sorry i am new to promises and if this were callbacks this is what i would do.

Susan Ho
  • 83
  • 2
  • 7

2 Answers2

11

If you want to loop and serialise the promises, not executing any other get calls once one fails, then try this loop:

async function getAllResults() {  // returns a promise for 250 results
    let totalResults = [];
    try {
        for (let i = 0; i < 5; i++) {
            totalResults.push(...await getResults.get());
        }
    } catch(e) {};
    return totalResults;
}

This uses the EcmaScript2017 async and await syntax. When not available, chain the promises with then:

function getAllResults() {
    let totalResults = [];
    let prom = Promise.resolve([]);
    for (let i = 0; i < 5; i++) {
        prom = prom.then(results => {
            totalResults = totalResults.concat(results);
            return getResults.get();
        });
    }
    return prom.then(results => totalResults.concat(results));
}

Note that you should avoid the promise construction anti-pattern. It is not necessary to use new Promise here.

Also consider adding a .catch() call on the promise returned by the above function, to deal with error conditions.

Finally, be aware that concat does not modify the array you call it on. It returns the concatenated array, so you need to assign that return value. In your code you don't assign the return value, so the call has no effect.

See also JavaScript ES6 promise for loop.

trincot
  • 317,000
  • 35
  • 244
  • 286
  • 3
    You might want to start with `prom = Promise.resolve([])` so that you don't have to duplicate the `get` calls and concatenation, and count to 5 properly. – Bergi Mar 19 '17 at 16:28
  • thank you this is working nicely. Excellent suggestion – Susan Ho Mar 19 '17 at 17:27
8

Probably you just need Promise.all method. For every request you should create a promise and put it in an array, then you wrap everything in all method and you're done.

Example (assuming that getResults.get returns a promise):

let promiseChain = [];
for(let i = 0; i <5; i++){
    promiseChain.push(getResults.get());
}

Promise.all(promiseChain)
    .then(callback)

You can read more about this method here: Promise.all at MDN

EDIT You can access data returned by the promises this way:

function callback(data){
    doSomething(data[0]) //data from the first promise in the chain
    ...
    doEventuallySomethingElse(data[4]) //data from the last promise
}
Phugo
  • 400
  • 1
  • 10
  • How would you propose the OP gets the results from the get() calls using this approach? – rasmeister Mar 19 '17 at 15:37
  • thanks but this is returning the same 50 results 5 times – Susan Ho Mar 19 '17 at 17:18
  • In this case we need to know the `get` implementation. But if you do not want to have the maximum benefit from the async nature of promises, you could try to serialize the promises using (for example) async. Here's an overview of its functionalities http://caolan.github.io/async/ – Phugo Mar 19 '17 at 17:52