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.
- $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.
- $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"