Sequencing asynchronous functions in Angular: Ensuring one function runs before another

When working with a save function that requires you to call another function to retrieve the revision number and make an API call, both of which are asynchronous in nature, how can you ensure one function waits for the other to execute?

$scope.getRevision = function(callback){
    Api.Product.querymyProdById({ prodId: $scope.editProdId }).$promise.then(function(result) {
        if (result && result.length >= 1 && result[0].effectiveDate != $scope.editProdmyDate) {
            $scope.editProdRevision = result && result[0].revision + 1;
            callback();
        } else {
            $scope.editProdRevision = 100;
        }
    });
}

$scope.saveProd = function(){
     $scope.getRevision(function(){});

     Api.Product.save({
        id: $scope.ProdId;
        revision:$scope.editProdRevision
         -some code

}

In the above code, I want to ensure that the save API is not called until the prodRevision is obtained.

Do you have any suggestions on how to achieve this?

Answer №1

If you already have promises in place, avoid messing with callbacks. It's better to have your functions return a promise and utilize the then method for chaining calls.

$scope.fetchData = function(){
    return Api.Data.retrieveInfo(..).$promise...;
}

$scope.updateData = function() {
   return $scope.fetchData().then(function() {
        return Api.Data.update(...);
   })
}

Answer №2

Callbacks were created by the javascript deities for this specific purpose

$scope.saveProduct = function(){
     $scope.retrieveRevision(function(){
        // this section executes after the retrieval of the revision
        Api.Product.save({
           id: $scope.productId;
           revision:$scope.editProdRev
            -some code
        });
     });

}

Answer №3

An effective way to handle multiple async calls is by chaining them one after the other. Here's an example:

// Initial asynchronous GET request:
$http({
  method: 'GET',
  url: '/firstUrl'
})
.then(function successCallback(response) {
  // Callback for first request
  // Second async GET request:
   $http({
     method: 'GET',
     url: '/secondUrl'
   })
   .then(function successCallback(response) {

   }, function errorCallback(response) {

   });
}, function errorCallback(response) {
  // Error callback when first request fails
});

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

What is the limitation of including a string constant with "</script>" inside a <script> block?

I am genuinely curious about this: I thought that the following code would be valid within an HTML document: <script> var test = "<script>why? </script>"; </script> However, it turns out that this leads to an "unterminated str ...

Implementing a search filter in Vue.js using a nested for loop

I am currently working with a JSON object that contains nested objects and I need to iterate over them to extract data. Everything is functioning correctly, but now I want to implement a search/filter feature where the search is performed on the second lev ...

Having difficulty with Android's HttpURLConnection when accessing a secured AngularJS web application powered by Spring - getting a

Hey there, I've got this snippet of code in my backend for configuring web security using Spring Boot Security Starter: @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void ...

Aurelia's numerous applications spread across various pages

Currently, I am in the process of finalizing the initial release of a large-scale website built using PHP (Phalcon), MySQL, and JQuery. The technology stack may be a bit outdated, but it was originally prototyped years ago and due to various circumstances, ...

Utilizing an Ajax request for a polling system

I am in need of adding a polling mechanism to call a web service from my webpage. To achieve this, I am attempting to utilize an ajax call within a javascript page. However, I am fairly new to both ajax and javascript. Below is the code snippet that I have ...

Issue with incorrect date being retrieved in MongoDB response from a node server

My date in mongodb is structured as follows: ISODate("2020-08-03T00:00:00.000+05:30"), However, after querying the date, it appears like this: 2020-08-02T18:30:00.000Z I am looking to get the correct date of 2020-08-03. What could I be doing wr ...

Firefox only loads images and jquery after a refresh of the page

Upon initially accessing my site after clearing the cache (a jsp page from a spring app), I noticed that the images and styles were not being applied. However, upon refreshing the page (ctrl-r), everything loaded perfectly. In Firefox's console outpu ...

Is there a necessity for me to utilize the nodejs https module if my hosting service offers TLS Certificates?

As a first-time application deployer for real-life use, I am utilizing the Stripe API for payment handling. My plan is to deploy the Node.js application on Render host, which promises fully managed and free TLS certificates for all hosted applications an ...

JS showcase of object literals and their corresponding properties

Just starting out with Javascript and eager to learn about arrays of objects. I'm currently exploring how to display an object along with its properties. Here's an example showcasing the colors of different fruits: var fruitColor = {'apples ...

What is the best way to convert the information from a <SelectInput /> component or similar components into another language?

Within my React admin v3 application, When retrieving data from the servers for my entity, I receive a unique identifier called a slug. This slug is a special key that needs to be translated on the client side. Here is an example of my <CallMeBackCre ...

Exploring the functionalities of can-deactivate without incorporating routing

I'm facing an issue with a parent component and multiple child components. The parent component contains a form, while each child component also has its own form. Unfortunately, all child components share the same route as the parent component and hav ...

Conceal and reveal feature for multiple dynamic identifiers simultaneously

After submitting the form, I am dynamically creating buttons. <template name="workflow"> {{#each newaction}} <div class="btn-box" > {{> actioncardsubcontent}} <button type="button" class="cancelsub" >New Action</button&g ...

Cannot retrieve Global variables when using chrome.tabs.executescript in Chrome 55

After recently updating Chrome to version 55.0.2883.75, I encountered an issue with my self-developed Chrome Plugin used for parsing HTML files. In the plugin, I utilize chrome.tabs.executescript to retrieve data from a background HTML page. Previously, I ...

Exploring Bootstrap: Understanding column stacking and the requirement for a new row to stack upon resizing

I am currently mastering Angular and Bootstrap for a potential job opportunity, so I have decided to create a simple demo page. However, I am facing an issue with getting a new row to stack after the last div of the previous row when resizing. Initially, m ...

There seems to be an issue with the border displaying correctly within the div element

I am currently working on developing a tag input system, but I am encountering some CSS issues. What I am aiming for is to have a green border that surrounds and contains the 2 divs inside it, however, this is not happening as expected. You can see the fi ...

When using Vue with CSS3, placing an absolute positioned element within a relative wrapper can cause issues with maintaining the

Just starting out with Vue and diving into the world of CSS3! I'm currently working on a component that you can check out here: https://codesandbox.io/s/yjp674ppxj In essence, I have a ul element with relative positioning, followed by a series of di ...

Refresh your webpage automatically without the need to manually refresh after clicking a button using AJAX in HTML and PHP!

One issue I'm facing is that the page doesn't auto-refresh, although it loads when I manually refresh it. Below you can find my HTML and AJAX code along with its database details. The Trigger Button <?php $data = mysqli_ ...

Dynamically add a plugin to jQuery during execution

After installing jQuery and a jQuery-Plugin via npm, I am facing the challenge of using it within an ES6 module. The issue arises from the fact that the plugin documentation only provides instructions for a global installation through the script tag, which ...

Experimenting with the inner workings of a method by utilizing vue-test-utils alongside Jest

Is there a way to properly test the internal logic of this method? For instance: async method () { this.isLoading = true; await this.GET_OFFERS(); this.isLoading = false; this.router.push("/somewhere"); } This method toggles isLoading, ...

A Guide to Implementing Inner CSS in Angular

I am working with an object named "Content" that has two properties: Content:{ html:string; css:string } My task is to render a div based on this object. I can easily render the html using the following code: <div [innnerHtml]="Content.html"& ...