How to create a promises loop

so I have a promise that collects data from the server, but only collects 50 responses at a time. I have 250 answers to collect.

I could just flesh out promises together as shown 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 case, I need only 250 results, so this seems like a manageable solution, but there is a way to link promises in a loop. so I run the loop 5 times and fulfill the following promise every time.

Sorry, I'm new to promises, and if these were callbacks, this is what I would do.

+6
source share
2 answers

promises, get, , :

function getAllResults() { // returns a promise for 250 results
    let totalResults = [];
    let prom = getResults.get();
    for (let i = 0; i < 4; i++) { // chain four more times
        prom = prom.then(results => {
            totalResults = totalResults.concat(results);
            return getResults.get();
        });
    }
    return prom.then( results => totalResults.concat(results) );
}

, -. new Promise.

.catch() , , .

, , concat , . , . , .

+7

, Promise.all. , all, .

(, getResults.get ):

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

Promise.all(promiseChain)
    .then(callback)

: Promise.all MDN

, promises :

function callback(data){
    doSomething(data[0]) //data from the first promise in the chain
    ...
    doEventuallySomethingElse(data[4]) //data from the last promise
}
+8

Source: https://habr.com/ru/post/1015875/


All Articles