我在Angular控制器中有以下代码......
function doWork() {
// show the loading modal
$scope.modal = $ionicLoading.show({
content: 'Fetching current location...',
showBackdrop: false
});
console.log("get orig pos");
// get the position
PositionService.getPosition(posOptions)
.then(function(positionArr) {
// got 1st location // this doesn't execute!
console.log("got original pos: " + positionArr.length);
$scope.locationArray = positionArr;
$scope.dataReceived = true;
$scope.modal.hide();
}, function(err) {
// something went wrong
console.log("something wrong in getPos");
$timeout(function() {
$scope.modal.hide();
}, 3000);
});
console.log("get next pos");
PositionService.getPosition(posOptions)
.then(function(positionArr) {
// got 2nd location // this does execute!
console.log("got new pos: " + positionArr.length);
$scope.locationArray = positionArr;
$scope.dataReceived = true;
}, function(err) {
// something went wrong
console.log("something wrong in getPos");
});
}
当我运行程序时,PositionService.getPosition
函数被调用两次,正如我所期望的那样,但只执行了一个then
部分。不应该执行两个then
块,还是我误解了Javascript中的工作方式?这是getPosition
函数的内容......
getPosition : function(posOptions) {
return $cordovaGeolocation
.getCurrentPosition(posOptions)
.then(function(position) {
positionArr = positionArr.concat({
position: position,
status: 'new'
});
return positionArr;
}, function(err) {
console.log("PositionService: error getting position");
return err;
});
},
编辑:
这是控制台输出的请求...
答案 0 :(得分:1)
您应该链接您对位置服务的调用:
var p1 = PositionService.getPosition(posOptions)
.then(function(positionArr) {
// got 1st location
console.log("got original pos: " + positionArr.length);
$scope.locationArray = positionArr;
$scope.dataReceived = true;
$scope.modal.hide();
}, function(err) {
// something went wrong
console.log("something wrong in getPos");
$timeout(function() {
$scope.modal.hide();
}, 3000);
});
var p2 = p1.then (function() {
return PositionService.getPosition(posOptions);
}).then(function(positionArr) {
// got 2nd location
console.log("got new pos: " + positionArr.length);
$scope.locationArray = positionArr;
$scope.dataReceived = true;
}, function(err) {
// something went wrong
console.log("something wrong in getPos");
});
答案 1 :(得分:0)
首先.then()回调是一次成功'另一个是错误'。所以它是这两者中的一个。防爆。 http请求可以是' 200'或者' 404' (或其他错误)。
请参阅:http://blog.mediumequalsmessage.com/promise-deferred-objects-in-javascript-pt1-theory-and-semantics