Promise for-loop with Ajax requests

I am creating my own JavaScript application that loads Ajax calls into the same process at a specific time. Instead of going through a regular loop and doing everything at once, I thought I would wait for the Ajax call to complete, and then do the following.

Using Stackoverflow, I was able to do this as follows:

function ajaxCall(index) { return new Promise(function(resolve) { // Ajax request { resolve(); // } }); } Promise.resolve(0).then(function loop(i) { if (i < length) { return ajaxCall(i).thenReturn(i + 1).then(loop); } }).then(function() { // for loop complete }); Promise.prototype.thenReturn = function(value) { return this.then(function() { return value; }); }; 

However , this is too slow for me. I want to be able to store a var that keeps track of how many Ajax calls are currently in progress so that I can limit the number.

I tried several things, but I continue to work in endless cycles or do not get the desired result.

How to make a few number-limited asynchronous Ajax calls using the Promise for loop?

+2
source share
1 answer

It looks like you want a version of Promise.all that accepts an array of asynchronous functions, not promises, and a ceiling on the number of simultaneous operations. Sort of:

 Promise.allFuncs = (funcs, n) => { n = Math.min(n, funcs.length); var results = []; var doFunc = i => funcs[i]().then(result => { results[i] = result; // store result at the correct offset if (n < funcs.length) { return doFunc(n++); } }); // start only n simultaneous chains return Promise.all(funcs.slice(0, n).map((p, i) => doFunc(i))) .then(() => results); // final result }; // --- Example: --- var log = msg => div.innerHTML += msg + "<br>"; var wait = ms => new Promise(resolve => setTimeout(resolve, ms)); var example = ['a','b','c','d','e','f'].map(name => () => (log("started "+name),wait(2000).then(() => (log("ended "+ name), name)))); Promise.allFuncs(example, 2) .then(results => log("Results: "+ results)) .catch(log); 
 <div id="div"></div> 
0
source

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


All Articles