我在同步做angularjs函数有一个大问题。 我已经尝试过承诺和回调,但没有一个可以工作。同步angularjs函数
initMap().then(function(result){
console.log("in initMap");
getLocation().then(function(result){
console.log("getLocation");
if(result){
getPlaces.getData(map,myLatlng).then(function(data){
Array = data;
console.log("markersArray = ", markersArray);
}).catch(function(){
console.log('testtesttest');
})
}else{
console.log("error in getLocation");
}
}).catch(function(){
console.log("getLocationError");
})
}).catch(function(error){
console.log("bbbbb");
})
函数 'initMap()' 有
{
var defer = $q.defer();
//Codes...
defer.resolve(data);
return defer.promise;
}
,从而功能 '的getLocation' 和.service'getPlaces'
然而,他们都异步进行的。 控制台打印为:
in initMap <-- 1
getLocation <-- 2
error in getLocation <-- 3
数1应该不被打印,直到initMap()得到解决。 因此,在解决getLocation之前不应打印第2和第3个数字,并检查结果为false或true。
我现在真的处于死路一条。
请帮忙。 任何建议都可以。 示例代码非常感谢。
预先感谢您。
Pawas
编辑: 每种方法的代码如下。
噢。我在离子平台上做这个。 这是否会影响angularjs的工作方式? 以及如何解决该问题?
'initMap'
var mapOptions = {
center: myLatlng,
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var mapVar = new google.maps.Map(document.getElementById("map"), mapOptions);
$scope.map = mapVar;
console.log("initMap");
var defer = $q.defer();
defer.resolve('initMap');
return defer.promise;
'的getLocation'
var defer = $q.defer();
var suc = false;
navigator.geolocation.getCurrentPosition(function(pos){
myLatlng = new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude);
$scope.map.setCenter(myLatlng);
suc = true;
},function(error){
suc = false;
},{
timeout: 12000
});
defer.resolve(suc);
return defer.promise;
'getPlaces':
Sorry, this one I can't post the code.
在当前的情况下发生了什么,你只给了预期的结果..你还可以共享代码'initMap','getLocation'和'getPlaces'吗? –
它看起来像是根据你的描述做它应该做的。一个问题:'getLocation'中解析的值在'true'时被处理为错误,这是否是正确的行为? –
Pankaj Parkar:等几分钟。我将编辑 –