同步angularjs函数
发布时间:2020-12-17 17:16:40 所属栏目:安全 来源:网络整理
导读:我在同步制作 angularjs函数时遇到了很大的问题. 我尝试过承诺和回调,但没有一个有效. initMap().then(function(result){ console.log("in initMap"); getLocation().then(function(result){ console.log("getLocation"); if(result){ getPlaces.getData(map
我在同步制作
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. 我现在真的处于死路. 请帮忙. 先感谢您. Pawas 编辑: 哦耶.我在离子平台上这样做. ‘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; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |