我需要命令执行。一旦调用,我需要确保我的COMPLETE coords()方法完成。如何添加承诺或$ q?我尝试在控制台上打印,并在执行了最后一行coords()函数后找到了for co中的每个循环。见下面的代码。我非常喜欢角度帮助
var appa = angular.module('appa',['firebase','uiGmapgoogle-maps']);
appa.controller('mainCtrl', function($firebaseObject,$scope,$q) {
$scope.coords = function(){
var ref = firebase.database().ref();
var latArray = [];
var lngArray = [];
var cenlat;
var cenlng;
var marker = [];
ref.once("value")
.then(function(snapshot)
{
snapshot.forEach(function(child)
{
latArray.push(child.child("Lat").val());
console.log(child.child("Lat").val());
lngArray.push(child.child("Long").val());
var mark = {
id: child.child("Id").val(),
coords: {
latitude: child.child("Lat").val(),
longitude: child.child("Long").val()
},
options: { title: child.child("Alt").val() }
};
marker.push(mark);
CONSOLE.LOG("wWHY IS THIS PRINTED aFTER??? AND HOW TO HANDLE THIS ??");
});
cenlat = (Math.max.apply(Math,latArray)+Math.min.apply(Math,latArray)/2);
cenlng = (Math.max.apply(Math,lngArray)+Math.min.apply(Math,lngArray)/2);
});
$scope.map.center.latitude = cenlat;
$scope.map.center.longitude = cenlng;
CONSOLE.LOG("wWHY IS THIS PRINTED BEFORE??? AND HOW TO HANDLE THIS ??");
});
};
$scope.map = {
center:
{
latitude: 51,
longitude: 4
},
zoom: 2
};
$scope.coords();
});
答案 0 :(得分:0)
您正在使用firebase,并且可以轻松检查将它们存储在变量中的返回子项。然后在forEach循环中递减变量。
//initialized var a, is having child count
a = snapshot.numChildren();
下面的完整代码将创建有序执行并具有承诺的基本实现。我已经添加了console.log来显示顺序。我希望它有所帮助。
//complete code
var appa = angular.module('appa',['firebase','uiGmapgoogle-maps']);
appa.controller('mainCtrl', function($firebaseObject,$scope,$q){
$scope.coords = function(){
var q = $q.defer();
var ref = firebase.database().ref();
var latArray = [];
var lngArray = [];
var cenlat;
var cenlng;
var a="0";
var marker = [];
ref.once("value")
.then(function(snapshot)
{
a = snapshot.numChildren();
console.log(a);
snapshot.forEach(function(child)
{
latArray.push(child.child("Lat").val());
console.log(child.child("Lat").val());
lngArray.push(child.child("Long").val());
var mark = {
id: child.child("Id").val(),
coords: {
latitude: child.child("Lat").val(),
longitude: child.child("Long").val()
},
options: { title: child.child("Alt").val() }
};
a= a-1;
console.log("this is current"+a);
marker.push(mark);
});
console.log("hi"+a);
console.log("going for cenlat"+cenlat);
cenlat = (Math.max.apply(Math,latArray)+Math.min.apply(Math,latArray)/2);
console.log("done with cenlat"+cenlat);
console.log("going for cenlng"+cenlng);
cenlng = (Math.max.apply(Math,lngArray)+Math.min.apply(Math,lngArray)/2);
console.log("done with cenlng"+cenlng);
$scope.map.center.latitude = cenlat;
$scope.map.center.longitude = cenlng;
if(a==0){
q.resolve('resolved');
}
else{
q.reject('rejected');
}
});
};
$scope.map = {
center:
{
latitude: 51,
longitude: 4
},
zoom: 2
};
$scope.coords().then(
function(v){
console.log(v);
},
function(err){
console.log(err);
});
});