admin管理员组

文章数量:1220944

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.

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.

Share Improve this question asked Mar 19, 2017 at 14:42 Susan HoSusan Ho 832 silver badges7 bronze badges 5
  • 1 Does get return a promise? – T.J. Crowder Commented Mar 19, 2017 at 14:45
  • I would recommend checking out the async library for this. It'll make your life way easier. Look at the async.eachLimit functionality. – forrestmid Commented Mar 19, 2017 at 14:46
  • @forrestmid No, that does not work well with promises. – Bergi Commented Mar 19, 2017 at 15:46
  • Use recursion with promises. Or async/await if you insist on a loop. – Bergi Commented Mar 19, 2017 at 15:47
  • 6 How to create a loop of promises -> Get married?! – Ed Heal Commented Mar 19, 2017 at 16:00
Add a comment  | 

2 Answers 2

Reset to default 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.

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
}

本文标签: javascriptHow to create a loop of promisesStack Overflow