Reputation: 137
I have a 1.x AngularJS application, and need to perform 2 SQL queries synchronously (one after the other). The first does an update to a table, the second does a select against the same table to get the updated values. The problem I am encountering is that the queries are executed asynchronously, and occassionally the select is performed before the update completes, and I get back the "before" data rather than the "after" data. I put in a 500ms delay, and that works fine for me, but offshore folks with slower connections still encounter the problem intermittently. My code is below (simplified to make my point). Any thoughts as to how I can get the second query to wait until the first is complete?
$scope.saveUser = function(origuid, uid, name) {
$http.get('/ccrdb/updateAdmin?origuid=' + origuid + '&uid=' + uid + '&name=' + name);
setTimeout(function() {
$http.get('/ccrdb/getAdmins').then(function(response) {
$scope.users = response.data.detail;
});
return true;
}, 500);
};
Upvotes: 0
Views: 56
Reputation: 21219
$http returns promises that resolve when the request is done, so do:
$scope.saveUser = function(origuid, uid, name) {
$http.get('/ccrdb/updateAdmin?origuid=' + origuid + '&uid=' + uid + '&name=' + name)
.then(function() {
return $http.get('/ccrdb/getAdmins');
})
.then(function(response) {
$scope.users = response.data.detail;
});
};
Upvotes: 4