function loadPage{
$('#spinner').show();
setupPage();
$('#spinner').hide();
}
function loadPage{
$('#spinner').show();
setTimeOut(function(){
setupPage();
$('#spinner').hide();
}, 0);
}
The DOM manipulation tasks are not executed until this task's stack clears. The spinner isn't shown until setUp is completed.
Add a task to execute when this stack clears.
Most I/O APIs are async:
Callbacks:
function doSomethingAsync(callBack){
setTimeout(function(){
//.....
callBack();
}, 200);
}
doSomethingAsync(function(){
//will be called after 200ms
});
Callbacks Hell:
function doSomethingAsync(callBack){
//...
}
doSomethingAsync(function(result){
//...
doSomethingAsync(function(result){
//...
doSomethingAsync(function(result){
//...
});
});
});
function doSomethingAsync(callBack){
//...
}
var promise = doSomethingAsync();
promise
.then(function(result){
//...
if(!ok) throw new Error();
return doSomethingAsync2();
})
.then(function(result2){
//...
}, function(reason){
// Handle the error
});
Angular uses promises for everything that is async:
//Service
function doSmth(){
defered = $q.defer();
asyncOperation(function(error, data){
if (!error) defered.resolve(data);
else defered.reject(error);
});
return defered.promise;
}
//Controller
doSmth().then(function(value){
console.log(value);
}, function(err){
console.error(err);
});
console.log("The value will be shown after this.");
Result of $q.defer()
Result of deffered.promise
doSmth()
.then(function(value){
return value + 10;
},
errorFn,
notifyFn)
.then(function(value){
return $q.reject(new Error());
})
.catch(function(err){
console.err(err);
})
.finally(callbackFn);
The $http service is a function which takes a single argument β a configuration object β that is used to generate an HTTP request and returns a promise with two $http specific methods: success and error.
$http({method: 'GET', url: '/someUrl'})
.success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
})
.error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
*Since the returned value is a promise, you can also use then() for registering callbacks.
$http.get
$http.head
$http.post
$http.put
$http.delete
$http.jsonp
$http.patch