Managing promises individually within a promise.all() operation

While there is plenty of information available on handling errors with promise.all() and using catch, my goal is to handle each promise resolution within promise.all(). This is because I am working on setting up a customized progress bar in the console, and I want to trigger the tick method every time a promise resolves.

this.getNewSources = function () {
    var bar = new ProgressBar(':bar', {total: this.getSourceMap().size});
    var timer = setInterval(function () {
        bar.tick();
        if (bar.complete) {
            console.log('\ncomplete\n');
            clearInterval(timer);
        }
    }, 100);

    let promiseArr = [];
    for (let x of this.getSourceMap().values()) {
        promiseArr.push(this.requestArticles(x.getName(), x.getCat(), x.getKey()));
    }

    return Promise.all(promiseArr).then(() => {
        console.log("Articles loaded this round: " + this.articles.size);
        console.log('all sources updated');
        this.loadedArticles = true;
        console.log(this.articleCount);
        console.log(this.articles.size);
    }).catch(e => {
        console.log(e);
    });
};

I'm exploring possibilities to call the bar.tick() method whenever an individual promise resolves.

Answer №1

(Sharing a solution to my own question.)

To handle the situation, I included a then handler where I'm receiving the promise from the requestArticles function (pushing them into the promiseArr array). It was important for me to ensure that I pass the returned value out of the handler so it can be passed on to Promise.all, as indicated by the *** lines:

 this.getNewSources = function () {
    var bar = new ProgressBar(':bar', {total: this.getSourceMap().size});
    var timer = setInterval(function () {
        if (bar.complete) {
            console.log('\ncomplete\n');
            clearInterval(timer);
        }
    }, 100);

    function updateProgressBar() {
        bar.tick()
    }

    let promiseArr = [];
    for (let x of this.getSourceMap().values()) {
        promiseArr.push(this.requestArticles(x.getName(), x.getCat(), x.getKey())
            .then(value => {           // ***
                updateProgressBar();   // ***
                return value;          // ***
            })                         // ***
        );
    }

    return Promise.all(promiseArr).then(() => {
        console.log("Articles loaded this round: " + this.articles.size);
        console.log('all sources updated');
        this.loadedArticles = true;
        console.log(this.articleCount);
        console.log(this.articles.size);
    }).catch(e => {
        console.log(e);
    });
};

This setup ensures that my handlers are executed as promises complete individually. By returning the received value in the handler, the promise created by calling then will resolve with that value, which will then be recognized by Promise.all. Any rejections will bypass this handler and instead trigger the handlers connected via Promise.all.

Explore the ASCII progress library on npm

View result output in the console:

https://i.sstatic.net/yTTSA.gif


(Credit goes to T.J. Crowder for his initial insight, which inspired me to implement this approach when pushing onto the array. He suggested deleting his answer and having me share this instead.)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Adding elements to a JavaScript modal using a loop

When working with JavaScript, I am dynamically adding content to a modal. This involves populating different data into various table rows and cells within the modal. <table class="table table-striped"> <thead> <tr> ...

Dealing with validations in a personalized aid

Recently, I've been exploring CodeceptJs and have found it quite easy to work with. Currently, I'm utilizing it with NightmareJs for testing a gallery that retrieves data from an interface via JSONP to create a list of images enclosed in <div& ...

Using React and Jest to mock a default function imported from an npm package

I am attempting to mock the "readXlsxFile" function from the npm package "read-excel-file". My issue is most likely with the line jest.spyOn(readXlsxFile, "default"). I have tried various async/await combinations and also used the "act" method from react t ...

What guidelines should be followed for utilizing jQuery's Ajax convenience methods and effectively managing errors?

Imagine a scenario where I am trying to mimic Gmail's interface using jQuery Ajax to incorporate periodic auto-saving and sending functionalities. Error handling is crucial, especially in cases of network errors or other issues. Instead of just being ...

How to rotate an object in Threejs using the mouse without having to click and drag?

I'm searching for a solution to rotate around an object in Threejs without the need to hold down the mouse button. A good example can be found on this website: which utilizes Threejs. Despite searching through forums and documentation, I have been un ...

using javascript to access the window's global variables from another window

After opening a new window from a webpage using window.open(url);, I've defined some global variables in the original window. I am now trying to figure out how to access these variables in the newly opened window. Does anyone have a solution for this ...

Scroll effortlessly to the middle, bottom, and top of the page in vue.js using arrow keys for a seamless

I'm interested in implementing a feature that allows users to scroll smoothly up and down the page using the arrow keys. When the first down key is pressed, I'd like to smoothly scroll to the middle (50%) of the page, and when the second down ...

Unable to proceed, WISTIA upload frozen at 100% complete

I recently integrated the Wistia API for video uploads. Everything seemed to be working fine as per the Wistia documentation until I encountered an issue. After uploading a video file, the progress bar would reach 100%, but then an error was logged in the ...

After triggering an action, I am eager to make a selection from the store

To accomplish my task, I must first select from the store and verify if there is no data available. If no data is found, I need to dispatch an action and then re-select from the store once again. Here is the code snippet that I am currently using: t ...

Protecting client-side game logic operations with web application security

I've been developing a web-based game that utilizes the Canvas feature of HTML5. However, I've come to realize that there is a significant vulnerability in my system. The scoring and gameplay statistics are currently being calculated on the clien ...

Updating a d3.js force-directed graph may retain previous JSON data during the reloading process

Having a d3.js force-directed graph that pulls data from a JSON feed, I encounter an issue when clicking on a node. Although the updated JSON is correct, the displayed graph does not reflect this new data. It seems like the graph is retaining previous info ...

Cease the cropping function for Cropper.js when it extends beyond the boundaries of

Is there a way to prevent the crop corners from moving once the user drags the cursor out of the image while cropping? I encountered an issue where the cropped corners are displaced from the cursor when the user moves out of the image and then back in, wh ...

Use jQuery to place tags around the content of existing <li> elements

Using jquery, I have been able to successfully create a list by using the following code: $(list).append(item); (where list is the list reference and item consists of the $('<li>') elements being added). var item = $('<li>' ...

JavaScript's toLocaleDateString function defaults to displaying null values as 12/31/1969

Why does Javasript toLocalDateString convert null dates in my API to 12/31/1969? Is there a way to just display the nulls without this default behavior, or do I have to use conditional statements every time? const formatDate = (dateInput: string) => { ...

Automated Desk: adjust page through programming

I am currently utilizing Smart Table and I would like to automatically navigate to a specific page once the controller has been created and the table is displayed. After searching on stackoverflow, I came across this code snippet that allows me to achieve ...

Issues with single and double quotation marks in JQuery

I'm having trouble inserting a tag into the page. The tag contains both single and double quotes, so I tried storing that part in a variable named content. Can someone explain why this content variable isn't displaying onclick after the code runs ...

What would be the ideal alternative if the Google Ajax API is unavailable, given that Google does not allow for local installation?

On my website, I include the following script: ... <script type="text/javascript" src="https://www.google.com/jsapi"></script> ... This particular script is from Google and is used to dynamically load other resources, such as the Google Chart ...

Why do `setTimeout` calls within JavaScript `for` loops often result in failure?

Can you help me understand a concept? I'm not inquiring about fixing the code below. I already know that using the let keyword or an iffe can capture the value of i. What I need clarification on is how the value of i is accessed in this code snippet. ...

Is there a way to enhance the sensitivity of the contenteditable area on my website for touch events specifically on stock browsers on Android devices?

It has come to my attention that focusing and editing a contenteditable area on Android stock browsers can be quite challenging. For instance, when visiting the following link http://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_global_contenteditabl ...

Mongoose doesn't support saving extensive text-data

I am facing a challenge while trying to save an extensive text into my mongodb database as it keeps crashing. I am in the process of creating a snippet manager and below you can find the error code I encountered: { [MongoError: Btree::insert: key too larg ...