简体   繁体   中英

What is purpose of this angularJS code?

Could someone explain to me what this code does? I know that it fetches countries and push them to the list which is shown in a web page, but why? I think that $scope.countries = service.query() is enough or is this way to avoid Asynchronous Problems?

$q.all([$scope.address.$promise, $scope.countrys.$promise]).then(function() {
        if (!$scope.address.country.id) {
            return $q.reject();
        }
        return Country.get({id : $scope.address.country.id}).$promise;
    }).then(function(country) {
        $scope.countrys.push(country);

    });

Descriptions in code comments. This is conditionally data loading process using promise mechanism. Try to specify your question more detailed if is is not enough for you

// if address and countries was loaded (probably from ajax request)
$q.all([$scope.address.$promise, $scope.countrys.$promise]).then(function() {
    // if address doesn't exist reject all actions
    if (!$scope.address.country.id) {
        return $q.reject();
    }
    // otherwise load country based on address field as a promise
    return Country.get({id : $scope.address.country.id}).$promise;
}).then(function(country) {
    // when loading process is finished add country to dataset
    $scope.countrys.push(country);
});

According to $q service documentation

$q.all([promise1, promise2, ...])

Combines multiple promises into a single promise that is resolved when all of the input promises are resolved.

service.query() will inevitably return a promise , which resolves when the asynchronous call completes. It would make no sense to set the scope property (which you will no doubt bind to some form of list) with a promise.

What the code is doing is waiting for the promise(s) to resolve, performing some logic, and setting the resulting data to a scope property.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM