Using AngularJS to chain promises

After coming across some advice on AngularJS validation and promises, I am interested in creating a chain of confirmation dialogs to validate multiple steps at once.

By making an API call based on user input, we can determine what steps require confirmation from the user. For each step that needs confirmation, present the user with a prompt to decide whether to proceed to the next step. If any step returns false, the entire chain should return false.

While I have been learning about asynchronous JavaScript and promises, I still consider myself relatively new to this concept. How can I effectively chain these actions to obtain a final true/false result for all steps? Keep in mind that an API call is necessary to determine which information should be displayed to the user, hence the initial fetchSomeData() call in the chain.

Any assistance or recommendations on this matter would be greatly valued.

fetchSomeData = function() {
    var deferred = $q.defer();
    api.fetchData(param1, param2, param3)
        .then(function(data) {
        deferred.resolve(data.content);
    }, api.errorHandler);
    return deferred.promise;
}
// data = {condition1: false, condition2: true, condition3: true}
// display confirmation dialogs for Step 2 and Step 3, but not Step 1 

confirmStep1 = function(data) {
    if (data.condition1) {
        return confirmDialogService.popConfirm('step1').then(function(confirmed) {
            return confirmed;
        }, function() {
            return false;
        });
    } else {
        return $q.when(true);
    }
}

confirmStep2 = function(data) {
    if (data.condition2) {
        return confirmDialogService.popConfirm('step2').then(function(confirmed) {
            return confirmed;
        }, function() {
            return false;
        });
    } else {
        return $q.when(true);
    }
}

confirmStep3 = function(data) {
    if (data.condition3) {
        return confirmDialogService.popConfirm('step3').then(function(confirmed) {
            return confirmed;
        }, function() {
            return false;
        });
    } else {
        return $q.when(true);
    }
}

confirmSteps = function() {
    return fetchSomeData()
        .then(confirmStep1(data))
        .then(confirmStep2(data))
        .then(confirmStep3(data));
}

confirmSteps().then(function(allConfirmed) {
    if (allConfirmed == true) {
        doSomething();
    } else {
        return;
    }
});

Answer №1

dfsq began composing a response but decided to delete it, so I'm adding my perspective:

confirmSteps = function() {
    return fetchSomeData()
        .then(confirmStep1(data))
        .then(confirmStep2(data))
        .then(confirmStep3(data));
}

When calling functions, it's crucial to chain them rather than invoking them simultaneously. This is similar to setTimeout(alert("Hi"),5), where you want to wait before executing the alert message. It should be more like

setTimeout(function(){ alert("Hi"); }, 5)
;

confirmSteps = function() {
    return fetchSomeData()
        .then(confirmStep1)
        .then(confirmStep2)
        .then(confirmStep3);
}

To pass data to all three promises instead of just one, you can nest the structure like this:

confirmSteps = function() {
    return fetchSomeData().then(function(data){
        var v1, v2;
        return confirmStep1(data).then(function(d){ 
           v1 = d;
           return confirmStep2(data);
        }).then(function(d){
           v2 = d;
           return confirmStep3(data);
        }).then(function(v3){
            return v1 && v2 && v3;
        })
    });
};

This method works but can be improved by using short circuiting and centralizing error handling. The revised code would look like this:

confirmStep1 = function(data) {
    if (data.condition1) return $q.when(true);
    return confirmDialogService.popConfirm('step1');
};

confirmStep2 = function(data) {
    if (data.condition2) return $q.when(true);
    return confirmDialogService.popConfirm('step2');
};

confirmStep3 = function(data) {
    if (data.condition3) return $q.when(true);
    return confirmDialogService.popConfirm('step3'):
};

confirmSteps = function() {
    var data = fetchSomeData();
    return data.then(confirmStep1).then(function(soFar){ 
         if(!soFar) return false; 
         return data.then(confirmStep2); 
    }).then(function(soFar){ 
         if(!soFar) return false; 
         return data.then(confirmStep3); 
    }).catch(function(){ return false; });
};

Additionally, for optimization, the following code:

fetchSomeData = function() {
    var deferred = $q.defer();
    api.fetchData(param1, param2, param3)
        .then(function(data) {
        deferred.resolve(data.content);
    }, api.errorHandler);
    return deferred.promise;
};

Can be simplified to:

fetchSomeData = function() {
    return api.fetchData(param1, param2, param3).then(function(data) {
        return data.content;
    }, api.errorHandler);
};

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

The operation malfunctions if the variable input is below 50, causing it to produce inaccurate results

The function "calcFinalTotal()" was created to calculate the post-tax discount on a purchase of items that were previously totaled and stored in an input tag with the ID of "totaltaxamount". This function applies a 10% discount to orders between $50 to $ ...

Display HTML components depending on an object's property using AngularJS

Here is the code I have created to display a simple drop down list: var products = [ { "id": 1, "name": "Product 1", "price": 2200, "category": "c1" }, { "id": 2, "name": "Product 2", "p ...

Determine if the webpage is the sole tab open in the current window

How can I determine if the current web page tab is the only one open in the window? Despite searching on Google for about 20 minutes, I couldn't find any relevant information. I would like to achieve this without relying on add-ons or plugins, but if ...

Using AJAX and FormData to Attach a List upon Submission

I am currently working on connecting a list of "Product Specifications" to my "Add Product" dialog, and I'm using AJAX to submit the form. Since users are able to upload a product image within this form, I am sending the AJAX request with a 'For ...

best way to eliminate empty p tags and non-breaking spaces from html code in react-native

How can I clean up dynamic HTML content by removing empty <p> tags and &nbsp? The whitespace they create is unwanted and I want to get rid of it. Here's the HTML content retrieved from an API response. I'm using the react-native-render ...

Adjust the transparency and add animation effects using React JS

When working on a React project, I encountered an issue where a square would appear under a paragraph when hovered over and disappear when no longer hovered. However, the transition was too abrupt for my liking, so I decided to implement a smoother change ...

How can I incorporate a new user interface button into Here Maps?

I have set up a default interactive map using Nokia Here Maps v3. The map contains multiple markers grouped together. Now, I am looking to add a button or some other UI element to the map that, when clicked, will call a function to zoom in as tightly as p ...

Is it possible to continuously stream the latest data from my xammp server directly into my console log without relying on the set Interval function?

Is there a way to have the data automatically reflect updates in the database without relying on the setInterval function? var dataUpdate = setInterval(updateData, 1000); function updateData() { $http.get('URL CALL', { params: { ...

What circumstances allow @Inject to be optional in Angular?

My Angular service is simple yet causing errors. Here's the code snippet: // service.ts export class SimpleService { // ... } // component.ts @Component({ selector: 'my-component', templateUrl: 'components/mycomp/mycomp.ht ...

Techniques for adding values to arrays in JavaScript

My Anticipated Result let Album = { album_desc: AlbumTitle, id: 1, album_title: 'ss', AlbumDescription: 'sdsd', ImageName: 'image.jpg', album_pics: below array }; I am looking to dynamically p ...

What steps are necessary to add a Contact Us form to my HTML website?

Currently, I am searching for a way to add a "Contact Us" section to my website that is completely HTML-based. I believe the best approach would involve using a PHP script to handle sending emails from a form on the Contact Us page, but I am not familiar ...

Discover how to access the translations of a specific key in a chosen language by utilizing the angular $translate functionality

How can I retrieve a specific language translation using angular's $translate function within a controller? The $translate.instant(KEY) method returns the translation of the specified key based on the currently selected language. What I am looking for ...

Is there a way to shut down a browser tab without being asked, "Are you sure you want to close this window"?

Is there a way to gracefully close a browser window without being interrupted by the annoying Do you want to close this window prompt? I've noticed that whenever I attempt to use the window.close(); function, this prompt always pops up. ...

Creating multiple objects in a threejs instance with varying sizes and positions

Recently, I decided to try out the InstancedBufferGeometry method in order to improve performance when rendering thousands of objects. Specifically, I wanted to create instances of cube geometries with varying heights. AFRAME.registerComponent('insta ...

Tips for extracting tables from a document using Node.js

When converting an XML document to JSON using the xml-js library, one of the attributes includes HTML markup. After parsing, I end up with JSON that contains HTML within the "description":"_text": field. { "name": { ...

How to manipulate iframe elements using jQuery or JavaScript

Hey there, I have a simple task at hand: I have a webpage running in an iFrame (located in the same folder on my local machine - no need to run it from a server) I am looking to use JavaScript to access elements within this iFrame from the main page. How ...

Switching the checkbox state by clicking a button in a React component

Is there a way to update checkbox values not just by clicking on the checkbox itself, but also when clicking on the entire button that contains both the input and span elements? const options = ["Option A", "Option B", "Option C"]; const [check ...

What steps can I take to resolve my password validation rule when confirming during sign-up?

Utilizing react-hook-form in combination with Material-UI for my sign-up form has been a challenge. I am currently working on implementing a second password field to confirm and validate that the user accurately entered their password in the initial field, ...

The jQuery validation feature permits entering a code that falls within the range of user1 to user100

Here is an example where the user can only enter a code between 1 and 100. Otherwise, it will return false. var regexCode = /var regexEmail = /^0*(?:[1-9][0-9]?|100)$/; $(document).on('change','#code',function() ...

The issue of dynamic select not sending the POST data

Having an issue with a form where the selected country and city are not being posted correctly. Despite different names in the form and php mailer script, both selections are coming through as the country. Here's the form: <select style="width: 6 ...