[英]Angularjs promise wait for result
在我的angularjs應用程序中,單擊按鈕時有以下代碼:
if (!$scope.isChecked) {
$scope.getExistingName($scope.userName).then(function (data) {
$scope.userName = data;
});
}
//some processing code here then another promise
myService.save($scope.userName,otherparams).then(function (res) {
//route to page
}, function (err) {
});
這里的問題是,如果$ scope.isChecked為false,它將進入promise,並且由於花費時間來解決它,因此它進入了下一行代碼。 因此,$ scope.userName不會更新,並使用舊值代替返回的更新值。
最好的方法是什么?
如果myService.save需要等待$ scope.getExistingName Promise,只需在“ then”語句中計算該操作即可。
if (!$scope.isChecked) { $scope.getExistingName($scope.userName).then(function (data) { $scope.userName = data; myService.save($scope.userName,otherparams).then(function (res) { //route to page }, function (err) { }); }); } //some processing code here then another promise
您可以使用$q
。 首先,您必須在角度控制器中注入$q
。
//Create empty promise
var promise;
if (!$scope.isChecked) {
promise = $scope.getExistingName($scope.userName).then(function (data) {
$scope.userName = data;
});
}
// Wait or not for your promise result, depending if promise is undefined or not.
$q.all([promise]).then(function () {
//some processing code here then another promise
myService.save($scope.userName,otherparams).then(function (res) {
//route to page
}, function (err) {
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.