AngularJS:有没有更好的方法同步两个承诺?

时间:2013-08-05 16:39:16

标签: javascript angularjs

$http.get('/services/menu').success(function (dataMenu) {
    $http.get('/services/language').success(function (dataLanguage) {
            console.log('dataLanguage', dataLanguage);
            $scope.menuRoot = dataMenu.result.items;
            $scope.menuItems = dataMenu.result.items;
            $scope.languageRoot = dataLanguage.result;
            $scope.currentMenuItem = null;
            $scope.refreshExperiments();
            $scope.mergeLanguage();
    });
});

2 个答案:

答案 0 :(得分:25)

是的,您可以使用$q.all

并行运行它们
$q.all([$http.get('/services/menu'), $http.get('/services/language')])
   .then(function (res) {
        var dataMenu = res[0].data.result.items;
        console.log('dataLanguage', res[1].data);
        $scope.menuRoot = dataMenu;
        $scope.menuItems = dataMenu;
        $scope.languageRoot = res[1].data.result;
        $scope.currentMenuItem = null;
        $scope.refreshExperiments();
        $scope.mergeLanguage();
});

答案 1 :(得分:0)

可替换地:

var menuPromise = $http.get('/services/menu');
var languagePromise = $http.get('/services/language');

menuPromise.success(function(dataMenu) {
    languagePromise.success(function(dataLanguage) {
        console.log('dataLanguage', dataLanguage);
        $scope.menuRoot = dataMenu.result.items;
        $scope.menuItems = dataMenu.result.items;
        $scope.languageRoot = dataLanguage.result;
        $scope.currentMenuItem = null;
        $scope.refreshExperiments();
        $scope.mergeLanguage();
    });
});

同时生成两个$http个请求,然后在完成console.log... etc个承诺后运行代码块($http)。