2015-12-08 67 views
0

我在角控制器下面的代碼...混淆的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; 
     }); 
    }, 

編輯:

這裏的要求控制檯輸出...

image

+0

'。那麼()'應用於[承諾](HTTPS://www.promisejs .org /) - 這裏是[MDN文檔](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise),它解釋了它們是如何工作的。 –

+0

你能告訴我們你的控制檯輸出嗎? – Christoph

回答

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

好的。因爲我不關心對'PositionService'的調用的順序,所以我想我可以像對待'getPosition'一樣對多個異步調用進行調用。我沒有意識到在做出新的承諾之前我必須等待承諾的迴應。這與我認爲承諾的工作方式完全不同。這個限制在我讀過的任何文檔中都沒有提及,或者我誤解了它。 – CSharp