Don't continue to expect other promises if one of them comes back with a special

I am dealing with a situation where I need to validate data in multiple tables by utilizing a function called validateTables(). This function relies on an asynchronous helper function queryTable() to check each table through API queries. The requirement for validation is that every table must contain some data; if any table is empty, the queryTable() function will return false. Currently, I have grouped all these calls within a Promise.all() method which checks the resulting array for any false values. However, for better performance, I would prefer to stop waiting for the resolution of remaining promises as soon as one resolves to false. Using Promise.race() or .all() methods won't work because they focus on the timing and status of promise resolution, rather than the returned value. Is there a way to achieve this without sacrificing the parallel processing capability of async functions?

The code snippets for the generalized functions are:

async queryTable(query, params) {
        try {
            let returnData = [];
            for await (const returnItem of api.executeQuery(query, params)){
                returnData.push(returnItem);
            }

            if (returnData.length > 0) {
                return true;
            }
            return false;
        }
        catch (err) {
            throw new Error(`${JSON.stringify(err)}`);
        }
    }

async validateTables() {
       const allDataExists = await Promise.all([
                this.queryTable(query, params),
                this.queryTable(query2, params2),
                this.queryTable(query3, params3),
                // more tables can be added here
            ]);
            if (!allDataExists.includes(false)) {
                return 'OK';
            }
            return 'Invalid';
    }

Answer №1

The Promise.all method ensures that the promise will be rejected if any of the promises within it are rejected. One approach to handle this is by throwing a sentinel value instead of returning it, and handling it in a try/catch block around the await keyword.

async fetchTableData(query, params) {
    try {
        result = []
        for await (const item of fetchDataFromApi(query, params)){
            result.push(item)
        }

        if (result.length > 0) {
            return true;
        }
        throw false;
    }
    catch (error) {
        throw new Error(`${JSON.stringify(error)}`);
    }
}

async checkTables() {
    try {
        const dataValidation = await Promise.all([
            this.fetchTableData(query, params),
            this.fetchTableData(query2, params2),
            this.fetchTableData(query3, params3),
            // add more queries here
        ])
    } catch(exception) {
        if(exception instanceof Error) throw exception
        return 'Invalid'
    }
    return 'OK'
}

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

Grab and drop into place

I have been searching for solutions, but so far I haven't found anything that works for my specific case. I have an upload button that currently works on a click event, but I also want it to be able to drag and drop files for uploading. Here is the H ...

How can I trace the origin of a post request sent from a form?

When constructing an HTML form, I typically utilize <form action="/postRoute" method="post"> to submit a post request. However, while examining a form for which I needed the post request URL, I came across the following: <form action="index.cf ...

Adjust the size of the textarea to accommodate the number of lines of text

<script type="text/javascript"> function AutoGrowTextArea(textField) { if (textField.clientHeight < textField.scrollHeight) { textField.style.height = textField.scrollHeight + "px"; if (textField.clientHeight ...

What is the best way to retrieve the Hash value of an object in Typescript?

What is the process for obtaining the hash value of an object in typescript? For instance: let user:any = {name:'tempuser', age:'29'}; let anotheruser:any = {name:'iam', age:'29'}; if( Object.GetHashCode(user) === ...

What could be the reason that changing document.body would impact its future accessibility?

This particular block of code functions exactly as anticipated: let vw, vh [vw, vh] = [document.body.clientWidth, document.body.clientHeight] console.log(vw) However, the behavior of this next snippet is not what I expected. It appears that simply havi ...

Angular Material's dialog modal swiftly closes without delay

Could you please explain why the modal opens and then closes instantly when I click on the Create Project button? https://example.com/edit/angular-code I am trying to display a component within the modal using Angular Material. portafolio.component.ts ...

The offsetWidth of the nativeElement in Angular 2's ElementRef is consistently returning a value

Is there a way to retrieve the width of an element with a dynamic width using Angular 2? I can easily accomplish this with pure javascript, but not through Angular 2. constructor(private element: ElementRef) { // .... Obtaining the width let width = thi ...

What is the reason behind the never return value in this typescript template?

As demonstrated in this example using TypeScript: Access TypeScript Playground type FirstOrSecond<condition, T1, T2> = condition extends never ? T1 : T2 type foo = never extends never ? () => 'hi' : (arg1: never) => 'hi' ...

Is there a way for me to position my arrow beside the header while still keeping the toggle function intact?

Can anyone assist me in positioning my arrow next to the header text, which I toggle on click? I attempted placing the arrow <div> into the H1 tag, but then the toggle function stops working. Any help would be greatly appreciated! Please includ ...

Delving into the intricacies of Promises/A+ and the mechanics of Asynchronicity in Javascript

I am new to JavaScript programming and may have some questions that seem basic. I was recently following a tutorial on Spring Boot and React. The author used a library called "rest" (package.json - "rest": "^1.3.1") and mentioned it is a Promises/A+ based ...

Enhance user security with password updates in ASP.NET Core 6 and Angular

I am having trouble updating passwords for users through the API. It works fine when done directly, but not through Angular UI in my project that utilizes ASP.NET Core 6 Web API and Angular 13. Here is the code for the ASP.NET Core Web API: [HttpPut] [Rou ...

What could be preventing the Python server from successfully receiving and sending messages?

I have developed a chatbot using Python and now I want to integrate it into my React website. However, I am encountering an error while trying to send data from localhost:/3000 to the Python server at localhost:/5000: Could not proxy request /js/jquery-1. ...

tips for extracting data from a javascript chart without an internet connection

Recently, I've been exploring a website that contains a fascinating javascript chart displaying a simple time series. When hovering over the data points on the chart, a popup window reveals the exact value of each point. While I am aware of methods t ...

Create an array variable for services in Angular

My goal is to define this user as an array. users = new BehaviorSubject<any>([]); In my component, I am attempting to add the userID to the array. this.Service.users.push(userID); To subscribe to it, I use the following code: this.Service.users.su ...

Issue with Asp.Net MandatoryFieldValidator and JavaScript What You See Is What You Get Editor

Currently, I am utilizing the Javascript WYSIWYG tool from OpenWebWare along with Asp.Net's RequiredFieldValidator on a TextBox that is linked to the WYSIWYG. So far, everything is functioning properly, however, upon the first form submission attempt, ...

What methods can be employed to maintain a consistent width for a multi-line span that aligns with the content?

Inside a div, I have 2 spans. When the content of the first span is short enough to fit on one line, the span's width matches the text content and positions the second span next to it. If the content of the first span is long and causes it to wrap, t ...

Can you explain the purpose of the window.constructor and global.constructor functions in JavaScript?

Can someone explain the purpose of this function? I've been searching for information but can't find anything. I tested it in Firefox: window.constructor() // TypeError: Illegal constructor new window.constructor() // TypeError: Illegal constru ...

Listener for Select Lists in PHP and Javascript

Thanks for taking the time to read my question. I have a database where I store clients and licenses. Now in my PHP code, I want to assign licenses to clients. What I want is to create a select option where you can choose your license type, such as "Wind ...

Interacting with objects in a loaded OBJ model using ThreeJS

I have an obj model representing a map with tree objects. After successfully loading the model, I am trying to access one specific tree object named Tree1. How can I achieve this? Currently, my code looks like this: loader.load( 'map.obj', fun ...

What is the best way to store data retrieved from an asynchronous database callback in Nodejs with express?

After querying my sqlite3 database to verify user details, I encounter an issue when trying to store the retrieved data in a session variable or global instance. Despite being able to access the data within the callback function, it becomes undefined once ...