【问题标题】:convert js callback function to angular with promise .then使用 promise 将 js 回调函数转换为角度 .then
【发布时间】:2016-11-23 02:54:49
【问题描述】:

我将如何对这个 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]);
                }
            });
        }        
    }

【问题讨论】:

标签: angularjs angular-promise


【解决方案1】:

你可以这样做:

    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;
});

【讨论】:

    猜你喜欢
    • 2020-10-22
    • 1970-01-01
    • 2021-06-13
    • 2018-04-23
    • 2017-03-27
    • 1970-01-01
    • 2017-03-31
    • 2019-12-14
    • 2020-11-30
    相关资源
    最近更新 更多