Javascript only does one thing at a time
However, it can pass something off and remember to do it later, once the callback is triggeredÂ
// Callback style:
$http({
method: 'GET',
url: '/api/users/1'
}, function(res) {
return res.data;
})
// Promise style
$http({
method: 'GET',
url: '/api/users/1'
})
.then(function(res) {
return res.data;
})
// In service:
this.getData = function() {
return $http({
method: 'GET',
url: '/api/users/1'
})
}
// In controller:
service.getData().then(function(data) {
$scope.info = data;
})
var promise = $http.get('/api/data/');
// The value is a promise. Promises are 'thenable'
promise.then(function(data) {
console.log(data);
})
var promise = $http.get('/api/data/');
// The value is a promise. Promises are 'thenable'
promise.then(function(res) {
return res.data
})
.then(function(data) {
// This will be the data value
// returned from the earlier .then callback.
console.log(data);
})
step1(function (value1) {
step2(value1, function(value2) {
step3(value2, function(value3) {
step4(value3, function(value4) {
// Do something with value4
});
});
});
});
$http.get('/api/myinfo/')
.then(promisedStep2)
.then(promisedStep3)
.then(promisedStep4)
.then(function (value4) {
// Do something with value4
})
.catch(function (error) {
// Handle any error from all above steps
})