gpt4 book ai didi

javascript - 关于 Javascript 'then' 行为的困惑

转载 作者:行者123 更新时间:2023-12-03 08:10:53 24 4
gpt4 key购买 nike

我在 Angular Controller 中有以下代码...

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 block 都不应该被执行吗?还是我误解了它在 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;
});
},

编辑:

这是按要求的控制台输出...

image

最佳答案

您应该将您的调用链接到位置服务:

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");
});

关于javascript - 关于 Javascript 'then' 行为的困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34153918/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com