I am relatively new to JavaScript, and would appreciate your patience.
I am trying to chain my method calls to run asynchronously, but am a bit stuck.
I have done a lot of searching and tried various methods, but I am missing something.
The idea is to call one method after the other, but only once the first method has resolved.
I am using AngularJs
, and I am not sure whether to use $q
and $defer
, or simple method chaining, or something completely different...
I have seen the below method of chaining:
callFirst()
.then(function(firstResult){
return callSecond();
})
.then(function(secondResult){
return callThird();
})
.then(function(thirdResult){
//Finally do something with promise, or even return this
});
And this example of using $q
:
app.service("githubService", function ($http, $q) {
var deferred = $q.defer();
this.getAccount = function () {
return $http.get('https://api.github.com/users/haroldrv')
.then(function (response) {
// promise is fulfilled
deferred.resolve(response.data);
// promise is returned
return deferred.promise;
}, function (response) {
// the following line rejects the promise
deferred.reject(response);
// promise is returned
return deferred.promise;
})
;
};
});
Below is my main function, and which method would be best for my purposes, and how would I implement the best solution?
NOTE: At this stage in my controller
, my data has already been returned from my API
call, and I am simply using the data to populate graphs and data grids:
function formatDataAccordingToLocation(dataFromAPI) {
$scope.dataModel = DataModelService.dataLoaded();
dataFromAPI.then(function (data) {
$scope.totalItems = data.total_tweet_count;
if ($scope.volumeChartChanged) {
$scope.volumeChartChange = false;
configureVolumeChart(data);
}
else {
setSummaryPageData(data);
setTweetListPageData(data);
configureVolumeChart(data);
configureMostMentionedGraph(data);
configureFollowerGrowthGraph(data);
configureEngagementsGraph(data);
configureHashtagsGraph(data);
configureTweetsVsReTweetsGraph(data);
configureWordCloudGraph(data);
}
})
}
I know I am asking a lot, and would be very grateful for your help.
Research and resources:
https://docs.angularjs.org/api/ng/service/$q
https://schier.co/blog/2013/11/14/method-chaining-in-javascript.html