What is the implementation of booleans within the Promise.all() function?

I am looking to implement a functionality like the following:

statusReady: boolean = false;
jobsReady: boolean = false;

ready() {
  return Promise.all([statusReady, jobsReady]);
}

...with the goal of being able to do this later on:

this.ready().then(() => {
  // Perform actions here once everything is ready
});

If all conditions are already met, I would expect the promise to resolve immediately. If any condition is not met, it should wait until they are before resolving. This 'ready()' function can be utilized wherever I need to ensure that certain elements have completed loading.

Answer №1

Do you need help creating a promise that resolves when a list of booleans are all true?

I have developed a function that accomplishes this task. It accepts an object of boolean values as input and returns a promise that resolves when all the booleans become true.

Below is the implementation of the function:

function createPromiseForTrueBooleans(boolList) {
    return new Promise(function (resolve, reject) {

        var allTrue = true;
        Object.values(boolList).forEach(function (value) {
            if (!value) allTrue = false;
        }); 

        if (allTrue) {
            resolve();
        } else {
            var _actualData = Object.assign({}, boolList); 
            Object.entries(boolList).forEach(function ([name, value]) {
                Object.defineProperty(boolList, name, {
                    configurable: true,
                    set: function (newVal) {
                        var areAllTrue = true;
                        _actualData[name] = newVal;
                        Object.values(_actualData).forEach(function (val) {
                            if (!val) areAllTrue = false;
                        });

                        if (areAllTrue) {
                            Object.entries(_actualData).forEach(function ([key, val]) {
                                Object.defineProperty(boolList, key, {
                                    configurable: true,
                                    value: val,
                                });
                            });

                            resolve();
                        }
                    },

                    get: function () {
                        return _actualData[name];
                    }
                });
            });
        }
    });
}

To use this function, create an object with boolean values and pass it as an argument to the function. The promise returned will resolve when all the boolean values in the object become true.

var myBooleanList = {"ready": false, "completed": false};

createPromiseForTrueBooleans(myBooleanList).then(function () {
    console.log("All boolean values are now true!");
}, function (error) {
    console.error(error);
});

myBooleanList.ready = true;
myBooleanList.completed = true;

Feel free to check out the working example provided above!

The function utilizes :set and :get accessors for each key in the boolean object. The :set function triggers whenever a value is set and checks if all boolean values are true before resolving the promise.

If you'd like to learn more about :get and :set, check out this helpful article:

Answer №2

Boolean values cannot be used in the Promise.all() method. According to the documentation on MDN, only promises can be passed as arguments in the Promise.all() method.

Alternatively, you can create two additional promises that will resolve when the desired condition is met. It seems unclear how the two values in your code snippet are supposed to change to true. If you provide more information on this, we can assist you in structuring the code correctly.

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

Transform a Vue.JS project into a Nuxt.JS project

Is it possible to transform a Vue.JS project into a Nuxt.JS project? Vue.js Project If you want to view the complete Vue.JS project, click here. This project utilizes the npm package vue-conversational-form to convert web forms into conversations using ...

The line break refuses to concatenate

I've been grappling with trying to format and print a 9x9 2D JavaScript array into a grid, but for some reason I can't seem to get the line breaks right. Instead of displaying the array in a neat square grid, it's all coming out in a single ...

Angular 2's ngModel feature allows for easy data binding and manipulation, particularly

I currently have an array of objects structured like this... this.survey = [ {id: 1, answer: ""}, {id: 2, answer: ""}, {id: 3, answer: ""}, {id: 4, answer: ""}, {id: 5, answer: ""}, {id: 6, answer: ""}, {id: 7, a ...

The dirtyFields feature in React Hook Form is not accurately capturing all the fields that are dirty or incomplete,

I am facing an issue with one field in my form, endTimeMins, as it is not registering in the formState. I have a total of four fields, and all of them are properly recognized as dirty except for the endTimeMins field. It is worth mentioning that I am utili ...

Using a CSS style to modify a class based on another class at the same level in the hierarchy

I am working with a jQuery carousel that is adding an 'active' class to images within a div. Within the same div, there is also a span with a 'fade' class that has a CSS style of opacity: 0. Is there a way to change the CSS style of the ...

Importing Vue and Vuex modules from separate files

Recently, I encountered an uncommon issue. I decided to keep my main.js and store.js files separate in a Vue project. In the store.js file, I imported Vuex, set up a new vuex store, and exported it. However, when importing this file into main.js and settin ...

The key to subscribing only once to an element from AsyncSubject in the consumer pattern

When working with rxjs5, I encountered a situation where I needed to subscribe to an AsyncSubject multiple times, but only one subscriber should be able to receive the next() event. Any additional subscribers (if still active) should automatically receive ...

Exploring the use of jQuery/JS for parsing and working with JSON

Hi everyone, I need some assistance with displaying data from an array created by a PHP file using JS/jQuery. Currently, I am working on implementing a points system for ZetaBoards which you can check out here. The points will be shown below the user' ...

Dealing with an empty req.body parameter in a NodeJS function for a Rest API using ExpressJs and sequelize

Looking for assistance with integrating ExpressJS and sequelize. I have a main function (fullaccount.js) that needs to invoke two functions ("accoun.js" and "people.js") receiving data in "fullaccount.js" for processing. However, while req.body is ready in ...

Is the latest Swiper JS version compatible with outdated web browsers?

Seeking information on browser compatibility. I am interested in upgrading to the latest version 8.4.5 of Swiper JS for my project, currently using version 4.1.6. Upon examining their shared Github repository file .browserslistrc, I noticed changes that ta ...

Utilize jQuery to create a dynamic image swapping and div showing/hiding feature

I'm having trouble implementing a toggle functionality for an image and another div simultaneously. Currently, when the image is clicked, it switches to display the other div, but clicking again does not switch it back. Can someone please advise on wh ...

Passing variables from a template to TypeScript using ngFor

Need help passing a variable from a template to typescript using *ngFor loop. Currently, my code looks like this: <select (change)="onregionchange()" data-placeholder="Regions" class="form-control regions-select" id="regions" multiple> <opt ...

Having trouble maintaining the initial state of the first accordion in a foreach loop

I have a collapsible accordion here, which is functioning well with static data. Now, I have connected it to a database and am attempting to retrieve data from the database. Below is the code I have implemented so far in CodeIgniter, View: <div class= ...

How can I make the fullcalendar 'moreLink' popover stay open when clicking outside?

Currently, I am working with FullCalendar v6 on nextjs. One built-in feature that caught my attention is the event popover that appears when there are too many events, accessible by clicking "more." However, I am facing a challenge in preventing this pop ...

Using TypeScript in the current class, transform a class member into a string

When converting a class member name to a string, I rely on the following function. However, in the example provided, we consistently need to specify the name of the Current Component. Is there a way to adjust the export function so that it always refers ...

Using addClass and fadeIn simultaneously when hovering over an element

After writing JavaScript code that utilizes the JQuery library to swap classes on hover, I noticed that the transition between background images was quite abrupt. The code functions as intended, but I would prefer to incorporate a fadeIn and fadeOut effect ...

Looping inside a loop with Angular's ngFor

I am working on an Angular + Firebase app. Within one of my components, I am retrieving elements from the Firebase DB and binding them into a template using *ngFor: <div *ngFor="let comment of (comments | async)> <div>{{ comment.text }}< ...

Preventing Vue.js from triggering watch on initial load

I need to implement a feature where a button is initially disabled and only becomes enabled when the input value is changed. To achieve this, I am using a boolean flag that is set to true by default and turns false only when the input changes. The v-model ...

Experience feelings of bewilderment when encountering TypeScript and Angular as you navigate through the

Exploring Angular and TypeScript for an Ionic project, I am working on a simple functionality. A button click changes the text displayed, followed by another change after a short delay. I'm facing confusion around why "this.text" does not work as exp ...

The HTTPOnly cookie is not accessible within the getServerSideProps function in Next.js

Why isn't the jid cookie available in getServerSideProps using Next JS? Here's the scenario: https://i.stack.imgur.com/FLRGk.png The jid cookie is generated by an Expressjs API at https://api-dev.example.com. I'm attempting to retrieve thi ...