Javascript promises: monitoring the state of an array

promise.all await
javascript promise all
promise.all parallel
promise.all for loop
promise.all error handling
promise map
promise.all object
promise.all concurrency

Let's say that I have an array of promises in Javascript, and I want them to resolve n promises at a time. What is a good way to do this?

Can I have a state array called promisesInProgress and have each promise monitor its length? On the outside, I will use Promise.all(). But within each promise, I want it to check the state array, promisesInProgress, and only fire when the length of that array is < n. Would that work?

What if I want to ensure that these promises don't resolve too fast, throttling them?

Is there a good pattern for this?

Promises "run" as soon as they come to existence, so when you have an array of those, you cannot expect to delay some of them.

What you could do however, is to work with an array of functions that -- when called -- would return a new promise. The max parameter would determine how many of those functions you would actually invoke immediately, while the remaining functions would only be called when "room" becomes available after one of the promises resolves.

Here is how you could do that:

// Main function. 
// Parameters:
// - the maximum number of unresolved promises that may exist at a given time
// - an array of promise-creating functions 
function throttle(maxPending, asyncFuncs) {
    return new Promise((resolve, reject) => {
        let numPending = 0;
        let nextFuncId = 0;
        const promisedValues = [];
        (function check() {
            if (nextFuncId >= asyncFuncs.length) { // All promises created
                if (numPending == 0) resolve(promisedValues); // All promises fulfilled
                return;
            }
            while (numPending < maxPending) { // Room for creating promise(s)
                numPending++;
                const thisFuncId = nextFuncId++;
                asyncFuncs[thisFuncId]().then(value => {
                    promisedValues[thisFuncId] = value;
                    numPending--;
                    check();
                }).catch(reject);
            }
        })();
    });
}

// Demo: 
// The usual delay function: returns a promise that resolves after given delay
const delay = (ms) => {
    console.log("Start delay of " + ms + "ms");
    return new Promise(resolve => setTimeout(resolve, ms))
            .then(() => console.log("End delay of " + ms + "ms"));
};

// Curry for the above: pass the milliseconds and return a function 
//   that can create a promise for it
const delayF = (ms) => delay.bind(null, ms);

// Pass 5 promise-creating functions, but only allow 3 concurrently pending promises:
throttle(3, [delayF(1000), delayF(500), delayF(800), delayF(300), delayF(900)])
    .then(() => console.log("all done"));  

Javascript promises: monitoring the state of an array, Let's say that I have an array of promises in Javascript, and I want them to resolve n promises at a time. What is a good way to do this? Can I have a state array� JavaScript Promises provide a mechanism for tracking the state of an asynchronous task with more robustness and less chaos. But first thing's first. JavaScript Promises support and Polyfill JavaScript Promises are part of the ECMAscript 6 standards and should be supported by all browsers eventually.

I want them to resolve n promises at a time. What is a good way to do this?

Use Promise.all:

const prom1 = Promise.resolve(1);
const prom2 = Promise.resolve(2);

Promise.all([prom1, prom2]).then(console.log);

Promise.all(), The returned promise is fulfilled with an array containing all the values logs, in order: // Promise { <state>: "pending" } // the stack is now empty� You can just use Promise.all on all inner arrays, then on the outer array, to get a promise for the array of arrays: Promise.all(promiseArrArr.map(Promise.all, Promise)).then(arrArr => …) Notice that Promise.all takes an array of promises, not an array of promise-returning functions.

First off, throttling is never the solution. You never want to stall the user experience. Without some code it's hard to determine what exactly you are attempting to do here, so an example would be nice.

There are a bunch of different ways to go about tracking the progress of a bunch of promises. But they mostly depend on what you want to track. Do you want to track when each individual promise is done? Simply refer to a function that increments a counter. To get the Progress Percentage simply do some basic math like below:

let promise_array = [...] // Your array of Promise objects
let counter = 0;
let total = promise_array.length

Promise.all(promise_array)

// inside each promise
counter++;

// to get progress
let progress = Math.round(counter/total*100,2)

If you want to get some other level of progress that occurs inside each promise then increment the counter whenever that progresses inside of each promise.

Improve async programming with JavaScript promises, In ES6, JavaScript Promises were added to the language spec, bringing about an If the returned promise fulfills, it is fulfilled with an array of all the values from the Our frontend monitoring solution tracks user engagement with your JavaScript frontends to give The state of React Native Web in 2019. Promise.all is actually a promise that takes an array of promises as an input (an iterable). Then it gets resolved when all the promises get resolved or any one of them gets rejected. For example, assume that you have ten promises (Async operation to perform a network call or a database connection).

I think Promise.all() can work for you : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

Example:

Promise.all([
  getData('https://my-json-server.typicode.com/typicode/demo/db'),
  getData('https://my-json-server.typicode.com/typicode/demo/db')
]).then(
  json => console.log(json), // JSON obj
).catch(
  err => console.log(err.message) // // ERROR ERROR //
);

JS Promises: race vs all vs allSettled, Promises have been around for a while now, but up until ES6, we of numbers in the array, and for every number, you need to double it, and Check out the full list of states and fates a Promise can have for more details. Our frontend monitoring solution tracks user engagement with your JavaScript� array.reduce is really useful for boiling an array down to a single value, which in this case is a promise. Let's put it all together: getJSON ( 'story.json' ) . then ( function ( story ) {

Beginner's Guide to JavaScript promises, JavaScript Promises provide a mechanism for tracking the state of an starts out with a state of pending, to indicate the asynchronous code it's monitoring Lets say we have an array of images we want to load and display� When a promise is in resolved or rejected states, a promise is said to be settled. So a promise generally transitions from pending state to settled state. Now that we know how promises are created we can look at how we can use or handle promises. This will go hand in hand with understanding the Promise object. Understanding promises Object

Promise, The Promise library API extends that of the JavaScript implementation. Please see the Chained State Handling example, below, for further guidance on using this Promise — A promise that resolves to an array of the resolved promise values, Serial Logging � Monitoring Device Disconnections � Disconnect/deep- sleep� If you need to synchronize different promises, Promise.all() helps you define a list of promises, and execute something when they are all resolved. Example: const f1 = fetch ( '/something.json' ) const f2 = fetch ( '/something2.json' ) Promise. all ([ f1 , f2 ]) . then ( res => { console . log ( 'Array of results' , res ) }) . catch ( err => { console . error ( err ) })

Deferreds and Promises in JavaScript (+ Ember.js example), In the course of its life, a Promise goes from a pending state, when it's Here the elements of an array are processed, and once all of them are� To summarize, the executor should perform a job (usually something that takes time) and then call resolve or reject to change the state of the corresponding promise object. A promise that is either resolved or rejected is called “settled”, as opposed to an initially “pending” promise.

Comments
  • If you don't want promises to resolve (yet), you should delay their creation. Once created, they do their thing. So when you have (an array of) promises, you're already too late to do anything about delaying resolutions. Could you provide a concrete example in your question?
  • Once promises are created, their settlement is out of your hands; that is the business of whatever asynchronous process(es) the promises represent. You (or rather your code) is only in charge of what happens once the promises (individually and/or collectively) have settled.
  • So you have two basic choices, (i) control the rate at which the asynchronous process(es) are called or (ii) call the asynchronous process(es) as quickly a possible then control the rate at which the responses are processed. These may be design choices, or other factors may dictate that you do one or the other.
  • @BorisK is the code clear enough or should I add explanations? Do you require a code example for promises throttling, or RxJS usage?
  • First off, throttling is never the solution yes it is - oftentimes async calls are costly (eg computationally intensive calculations, or calls to a not-free API) ;)
  • Perhaps you should read the following qualifying sentence, unless you believe throttling is okay in the context of the User Interface. Generally speaking it isn't, but since I imagine this comment was made in order to be technically correct rather than generally it won't matter.
  • I'm with @NinoFiliu, "First off, throttling is never the solution" is a poor opening sentence.
  • "You never want to stall the user experience.": the user experience may be harmed if you don't throttle, like when you query an API that has a maximum number of requests it allows to take in parallel. It would return errors and not the requested data.
  • This is a link-only answer that only addresses part of the qestion
  • @Nino It's not link only. See, e.g. meta.stackoverflow.com/q/381637/1364007. It is an answer with a link, not a link-only answer. Not a good answer, but it is borderline an attempt to answer the question.
  • I posted the comment before the edit, when it was a link-only answer