我对 JavaScript 比较陌生,希望您能耐心等待。
我正在尝试链接我的方法调用以异步运行,但有点卡住了。
我做了很多搜索并尝试了各种方法,但我遗漏了一些东西。
这个想法是在另一个方法之后调用一个方法,但只有在第一个方法解析后才调用。
我正在使用AngularJs
,并且我不确定是否使用$q
和$defer
,或者简单的方法链接,或者完全不同的东西......
我已经看到了以下链接方法:
callFirst()
.then(function(firstResult){
return callSecond();
})
.then(function(secondResult){
return callThird();
})
.then(function(thirdResult){
//Finally do something with promise, or even return this
});
这个使用 $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;
})
;
};
});
以下是我的主要功能,哪种方法最适合我的目的,以及我将如何实现最佳解决方案?
注意:在我的 Controller
的这个阶段,我的数据已经从我的API
调用返回,我只是使用用于填充图形和数据网格的数据:
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);
}
})
}
我知道我的要求很多,非常感谢您的帮助。
研究和资源:
https://docs.angularjs.org/api/ng/service/ $q
https://schier.co/blog/2013/11/14/method-chaining-in-javascript.html
最佳答案
根据 Paulson Peter 和 suzo 的良好反馈和评论,以下是我的问题的答案:
由于我的主函数 (formatDataAccordingToLocation
) 位于我返回的成功 $http
调用中,因此我无需将这些方法调用与 Promise 链接起来,这样做,延迟了我的执行。
关于JavaScript 方法链接或 Angular $q,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41115261/