3. function loadPage{
$('#spinner').show();
setupPage();
$('#spinner').hide();
}
function loadPage{
$('#spinner').show();
setTimeOut(function(){
setupPage();
$('#spinner').hide();
}, 0);
}
4. JavaScript is single threaded (*mostly);
Long running process will kill user experience:
UI elements will be unresponsive;
animations will pause
Long running task will timeout;
Most I/O APIs are async:
, , ;
Timers: setTimeout(), ;
Other APIs
5. The Event Loop is a queue of callback functions;
When an async function executes, the callback
function is pushed into the queue;
The JavaScript engine doesn't start processing the
event loop until all the code was executed;
The event loop is a first-in-first-out (FIFO) queue;
6.
7. 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){
//...
});
});
});
8. 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
});
9.
10. A promise is always async;
A promise represents a task that will finish in the
future;
A promise expose a function ( ) :
returns a new promise;
allows for the attachment of that will be
executed based on state;
handlers are guaranteed to execute in order
attached;
Promises become by a value;
Promises get by exceptions;
14. //Service
function doSmth(){
defered = $q.defer();
Result of
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.");
15. Result of
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);
16.
17. core Angular service for communication with remote
HTTP servers;
can communicate via the browser's
or via ;
works hand in hand with service.
18. $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 , you can also use for
registering callbacks.