将js回调函数转换为带有promise的角度。然后

时间:2016-11-23 02:54:49

标签: angularjs angular-promise

我将如何对这个js函数进行角度化?我需要它以异步方式使用。我的理解是.then和angular可以做到这一点。

    function showResult(result) {
        var lat = result.geometry.location.lat();
        var long = result.geometry.location.lng();
        $scope.vm.showroom.Longitude = long;
        $scope.vm.showroom.Latitude = lat;

    }

    function GetLatitudeLongitude(callback, address) {
        var address1 = address || '234 eisenhower avenue salt lake city';
        // Initialize the Geocoder
        var geocoder = new google.maps.Geocoder();
        if (geocoder) {
            geocoder.geocode({
                'address': address1
            }, function (results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    callback(results[0]);
                }
            });
        }        
    }

1 个答案:

答案 0 :(得分:5)

您可以这样做:

    function GetLatitudeLongitude(address) {
        address = address || '234 eisenhower avenue salt lake city';

        var deferred = $q.defer();
        // Initialize the Geocoder
        var geocoder = new google.maps.Geocoder();

        if (!geocoder) {
            deferred.reject('No geocoder available.');
            return deferred.promise;
        }

        geocoder.geocode({
            'address': address
        }, function (results, status) {
            if (status !== google.maps.GeocoderStatus.OK) {
                return deferred.reject('Geocoder status error.');
            }

            deferred.resolve(results[0]);
        });

        return deferred.promise;
    }

然后您可以像这样调用该函数:

GetLatitudeLongitude(address).then(function (result) {
    var lat = result.geometry.location.lat();
    var long = result.geometry.location.lng();
    $scope.vm.showroom.Longitude = long;
    $scope.vm.showroom.Latitude = lat;
});