gpt4 book ai didi

javascript promise 失败了

转载 作者:行者123 更新时间:2023-12-01 01:42:46 24 4
gpt4 key购买 nike

请帮忙...我做错了什么。

在我的 Controller 中,我有一个调用谷歌地理编码器的函数,我试图将其嵌入到一个 promise 中,以便在 $scope 中正确返回结果。我已经经历了 20 次不同的迭代,但仍然无法让它工作。这些函数有效,我正在得到结果...但我无法将结果放入 $scope...当尝试将地理编码器封装到 promise 中时,它给了我错误无法读取未定义的属性“then”

   function getPosition(thisLat,thisLon) {
// Retrieve address information based on Lat/Lng info

var q = $q.defer() ;
var thisLocation = getLL(thisLat,thisLon) ;
var addressInfo = {};
var notFound = 0 ;
geoCoder.geocode({'latLng': thisLocation}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
for (var x=0;x<results.length;x++) {
var googleInfo = results[x].address_components ;
for (var y=0;y<googleInfo.length;y++) {
addressInfo.fullAddress = results[x].formatted_address;
q.resolve(addressInfo) ;
}
}
} else {
return q.reject("none" ) ;
}
return q.promise ;
});
}

$scope.getEntrances = function() {
for (var x=0;x<$scope.park.entrances.length;x++) {
getPosition($scope.park.entrances[x].coordinates[0],$scope.park.entrances[x].coordinates[1])
.then(function(result) {
$scope.park.entrances[x].addressInfo = result ;
}) ;
}
}
$scope.getEntrances() ;

最佳答案

尝试兑现你的 promise q来自getPosition()函数本身,而不是来自geoCoder的回调函数。

简而言之,转移 return q.promise;getPosition()结束功能如下:

function getPosition(thisLat,thisLon) {
// Retrieve address information based on Lat/Lng info

var q = $q.defer() ;
var thisLocation = getLL(thisLat,thisLon) ;
var addressInfo = {};
var notFound = 0 ;
geoCoder.geocode({'latLng': thisLocation}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
for (var x=0;x<results.length;x++) {
var googleInfo = results[x].address_components ;
for (var y=0;y<googleInfo.length;y++) {
addressInfo.fullAddress = results[x].formatted_address;
q.resolve(addressInfo) ;
break; // [UPDATE] Avoid calling resolve on a promise multiple times
}
}
} else {
q.reject("none" ) ; // [UPDATE] Don't need a return statement here
}
});

// [UPDATE] return q.promise from here
return q.promise ;
}

关于javascript promise 失败了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52268536/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com