我在角控制器下面的代碼...混淆的Javascript「然後」行爲
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;
});
},
編輯:
這裏的要求控制檯輸出...
'。那麼()'應用於[承諾](HTTPS://www.promisejs .org /) - 這裏是[MDN文檔](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise),它解釋了它們是如何工作的。 –
你能告訴我們你的控制檯輸出嗎? – Christoph