JavaScript方法链接或Angular $ q

时间:2016-12-13 06:59:01

标签: javascript angularjs angular-promise method-chaining

我是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

Chain promises with AngularJS

https://schier.co/blog/2013/11/14/method-chaining-in-javascript.html

1 个答案:

答案 0 :(得分:0)

根据Paulson Peter和suzo的反馈和评论,以下是我的问题的答案:

由于我的主要功能(formatDataAccordingToLocation)位于我返回的成功$http调用中,因此我无需使用promises链接这些方法调用,并且这样做会延迟我的执行。

相关问题