我在同步制作
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
在解析initMap()之前,不应打印数字1.
因此,在解析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.
解决方法
您的问题是您在返回之前解决了承诺.
var defer = $q.defer(); <-- create the promise defer.resolve('initMap'); <-- resolve it return defer.promise; <-- returns a resolved promise
因此,您立即执行.then的调用.在getCurrentPosition中,您始终使用值false来解析您的承诺
var defer = $q.defer(); var suc = false; // Here,this is a callback executed asynchronously. So the code continue to executes navigator.geolocation.getCurrentPosition(function(pos){ myLatlng = new google.maps.LatLng(pos.coords.latitude,{ timeout: 12000 }); // This is resolve with the value false from the initialization of the variable above defer.resolve(suc); // Always returns a resolved promise with the value false return defer.promise;
代码的第一部分似乎是同步的.创建Google地图对象是同步执行的.你可以在承诺中改变它,但它有点无用.
对于getLocation,在异步回调中移动resolve.
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; defer.resolve(suc); },function(error){ suc = false; defer.reject(suc); },{ timeout: 12000 }); return defer.promise;