A pair of HTTP GET requests

How can I ensure that data is retrieved from a.json before moving on to b.json and then running the init function, given 2 JSON urls?

var urlA = "a.json";
var urlB = "b.json"; 

This is my approach:

var app = angular.module('calendarApp', []);
app.controller('ctrl', function($scope, $http) { 
  $http.get(urlA).success(function(data) {   }); 
  $http.get(urlB).success(function(data) {  
   init()}
);
var init = function(){}

Answer №1

When I first started out, I encountered the same issue.
There are several ways to tackle it just as suggested here.
Before delving into solutions, it's important to understand two key points:

1. JavaScript is synchronous

Example of Synchronous Execution[Flow in sequence]:
       console.log('1')
       console.log('2')
       console.log('3')

This would output 1 2 3.

An Example Involving Service Calls

   1. $http.get(aUrl).success(function(data) {  console.log('1.any time response returns')  });  
   2. $http.get(bUrl).success(function(data) { console.log('2.mummy returns')};

As JavaScript operates on a single thread, it will first make a call to $http.get(aUrl) which initiates the background data retrieval process.

  1. $http.get(aUrl).success(function(data) { console.log('1.any time response returns') });

It's crucial to note that the request with $http.get(aUrl) above doesn't wait for the response before moving on to the next request $http.get(bUrl), creating uncertainty about response timing.

  1. $http.get(bUrl).success(function(data) { console.log('2.mummy returns') }

The output could be either:

1.any time response returns

2.mummy returns

                     or

2.mummy returns

1.any time response returns

To address this challenge, we resort to asynchronous operations using various methods.

2. Asynchronous Calls

$http.get(aUrl)
    .then(function(response){
      console.log('inside the first then response');
      console.log(response.data);

      //performing the second request once the first one completes
     //and capturing the **outputResponse** for further processing in the subsequent **then** block
      return $http.get(bUrl);
    })
    .then(function(**outputResponse** ){
      console.log('outputResponse generated from second bUrl');
      //init() function can be called here 
    });

The above code meets your requirements.

For more information on utilizing $q in future, click here

Click here to understand why "then" is preferred over "success"

Answer №2

While this method may not be considered the most elegant or efficient, I found a quick way to make your code achieve its desired functionality:

let app = angular.module('calendarApp', []);
app.controller('ctrl', function($scope, $http) { 
  $http.get(aUrl).then(function(responseA) {   
      $http.get(bUrl).then(function(responseB) {  
         init()
      });
  }); 
});
let init = () => {}

Answer №3

If you're looking to streamline your code, consider implementing a service layer with two methods and then injecting this service into your controller:

//Controller
YourService.retrieveURL(urlA).then(function(response) {

            if(response != null && response.success == true){
                // perform an action
            }
            YourService.retrieveURL(urlB).then(function(response) {

                if(response != null && response.success == true){
                    // perform another action
                    init()
                }
            }, 
            function errorCallback(response) {

                console.log("Error: Unable to retrieve URL B ---> ");
            }); 
        }, 
        function errorCallback(response) {
            console.log("Error: Unable to retrieve URL A ---> ");
        });

// Example of a method in the service    
this.retrieveURL = function(urlA) {
    try{
        var deferred = $q.defer();

        $http({
            method: 'GET',
            url: getUrlA,
            params: {},
            responseType: "json",
            cache: false
        })
        .success(function(data, status, headers, config) {

            deferred.resolve(data);
        })
        .error(function(data, status, headers, config) {

            deferred.reject(data);
        });

        return deferred.promise;
    }catch(e){
        /* */
        console.log("Service Error: there was an issue retrieving the URL ---> " + e);
    }
}

Answer №4

When you use $http.get, it will return a promise, allowing you to execute the following actions:

return $http.get(urlOne)
    .then(function(response) {
        return $http.get(urlTwo);
    })
    .then(function(response) {
        return initialize();
    },
    function (error) {
        // Handle errors here
    });

Answer №5

If you want to improve efficiency in loading data asynchronously, I recommend utilizing AngularJS promises. One of the main advantages is that it allows data to be loaded concurrently without waiting for the completion of the initial request. Check out: https://docs.angularjs.org/api/ng/service/ $q

var promises = [];

var fetchData = function(url){
  var defer = $q.defer();

  $http.get(url).then(function(results){
    defer.resolve(results);
  }, function(err){
    defer.reject(err);
  });

  return defer.promise;
};

promises.push(fetchData('example.com/1.json'));
promises.push(fetchData('example.com/2.json'));

$q.all(promises).then(function(resultList){
  // Handle results here, resultList includes data from both API calls.
}, function(errList){
  // Manage errors here.
});

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

How to prevent the collapse action when clicking a button inside a div in Bootstrap 5 using data-bs-toggle

My div contains a data-bs-toggle attribute along with buttons. https://i.sstatic.net/RzagX.png When clicking on the panel, it collapses. However, I do not want this collapse event to trigger when clicking the buttons. Is there a way to control this behav ...

The exported JSON file from the editor is malfunctioning

After importing the obj file into the editor and exporting the geometry to a js file, I encountered an error in Firefox debug saying "Type Error: t1 is undefined". Interestingly, when I changed the model to the .js file exported by MaxExporter with both "E ...

An error occurred with Next.js and Lottie where the property "completed" could not be added because the object

Encountering an issue with Lottie's animation. Attempting to retrieve a JSON file (Lottie Animation) from Contentful and display it using the Lottie Component. However, facing an error message: "TypeError: Cannot add property completed, the object is ...

How to access a scope variable from a script in AngularJS

I'm currently working on a project using AngularJS and TimelineJS3, but I've hit a roadblock. In my application, I have a state called timeline, which has a partial view named timeline.html linked to a controller. This state initializes a promis ...

What causes a Next.js App to crash when a prop is not defined in destructuring code?

Let me share the issue I am facing. I have developed a custom Context API wrapper to handle all my data. However, there is this docType property that may not always be defined or may not exist at times. When I destructure it in this way: const { docType } ...

Trigger an AJAX request to execute a PHP script when a button is clicked

When I click a button, I want to run an ajax function that calls a PHP script and displays the resulting data under a specific div. However, it is not currently working as expected. Upon checking the console, I noticed that no value is being passed to the ...

Create a file object using content with the help of JavaScript

I am working with a file containing specific data const ics = 'BEGIN:VCALENDAR\n' + 'VERSION:2.0\n' + 'CALSCALE:GREGORIAN\n' + 'METHOD:PUBLISH\n' + 'END:VCALENDAR\n'; I am trying t ...

Swapping the non-DOM element text with another content

Currently facing an issue in my project where I need to replace plain text inside a contenteditable element without being enclosed in a DOM element. Here, I'm extracting the textNode using window.getSelection(); and looking to perform a text replaceme ...

What is the best way to implement setState in this scenario?

Receiving warnings in the console that say: Avoid changing state directly. Instead, use setState() method: react/no-direct-mutation-state When I tried changing this.state.turn = this.state.turn === 'X' ? 'O' : 'X'; to this.s ...

The process of updating a nested object property in Redux and React

Initially, the user object is established with properties such as name, color, and age using the SET_USER method. I need to modify the name property within the user object utilizing UPDATE_USER_NAME. However, despite trying a nested loop within UPDATE_USER ...

Vanish and reappear: Javascript block that disappears when clicked and shows up somewhere else

My goal is to make three squares randomly disappear when clicked on the page. However, I am facing an issue where some of them, usually the 2nd or 3rd one, reappear elsewhere on the page after being clicked. I have created a jsfiddle to demonstrate this: ...

Creating a Node API that can patiently listen for external data

My current project involves building a server that fetches data from an external API and returns it to the endpoint localhost:3000/v1/api/. However, I'm facing a challenge where the data retrieval process takes approximately 2 seconds, leading to empt ...

There are multiple sets of radio buttons within nested ng-repeats, but only the final group displays the selected value

I am having an issue with updating a form that contains multiple radio buttons based on data retrieved from an API. The challenge is that only the last set of radio buttons displays the value correctly. Below is the code snippet I am using (angular bracket ...

Initiate an AJAX call with various data formats included

I am currently developing an application that allows users to input values through an interface and send AJAX requests (similar to a REST API). My question pertains to sending data of multiple types in a single request. For example, here is a scenario: F ...

Execute npm build in sbt for play framework

Exploring sbt/play configuration is a new challenge for me. Working with play 2.3.8 to host my javascript application, my project utilizes: .enablePlugins(SbtWeb) .enablePlugins(play.PlayScala) .settings( ... libraryDependencies ++= WebDependancies :+ ...

Incorporating `ngRepeat` to populate options within a <select> element

Attaching data to each row and modifying it based on conditions I want to attach data to each individual row in Angular and also be able to modify that data depending on certain conditions. <select id="subject" name="subject" ng-mo ...

What could be the reason my "mandatory" function is not providing any output?

Recently, I've been working on an Express.js application that handles POST requests with a "city" parameter in the body. The application processes this request and utilizes an external service for further operations. To maintain clean code, I separate ...

Is there any variation in the Stripe payments Workflow when utilizing the Connect-API?

I have a question about simplifying the implementation of the Stripe API for multiple products on a single page. Currently, I have a webpage with 20 different items and I am utilizing Stripe Connect. Instead of creating individual forms for each product i ...

Can you explain the function of "app.router" in the context of Express.js?

When looking at the default app.js file generated by express.js, I came across the following line: ... app.use(app.router); ... This particular line of code has left me perplexed for a couple of reasons. First, upon consulting the express api documentati ...

retrieving a single object from $resource by passing a non-ID parameter

I am utilizing $resource to retrieve an array of objects. The method I am invoking is as follows: fetchTeamResource(): ng.resource.IResourceClass<ITeamResource> { return this.$resource("/api/Teams:teamId"); } Below is how I am i ...