asynchronous development in javascript
TRANSCRIPT
Asynchronous developmentin JavaScript
Why?
Performance
responsiveness
When?
Long running operations
Calculation
Network
File access
JavaScript vs Other Languages
C++, Java, C# -- Multiple threads
JavaScript -- Single threaded -- Uses event driven programming model
The Event Loop
The web browser trigger events, such as mouseevents, keyboard events DOM events, etc.
The event is queued into the event loop.
Each time, the JavaScript thread takes the nextevent and execute it.
When it �nish to handle the event, it takes thenext one.
JavaScript does one thing at a time?
The browser expose a set of asynchronousfunctionalities.
The commons are network operation such asHTTP requests, local storage operations etc.
The web browser uses a C++ libraries (Usually)that uses threads and run the “long running”operation on them.
When the operation is over it will trigger an event(success or failure).
The browser (through the event loop) will executethe attached functionality.
Callback
Asynchronous objects allow to attach a callback tothe execution of the function.
The callback is a function that will be called as theoperation ended.
Implementation of a callback looks like this:
function AsyncCall(callback) { // create the async object var worker = new worker(); // register on the 'finish' event worker.onfinish = function() { // run the callback callback(worker.response); } // run the workload worker.doWork(); }; asyncCall(function(){ alert(“finish!); });
Callback hell
Using callbacks can caused a different type ofproblem:
Assuming we need to do a series of operations.Each operation depends on the success of itsprevious.
The code can become messy.
Reviewing, debugging and �xing the code hadbecome a very hard thing to do.
Our code will look like a spaghetti:
asyncCall(function(response) { If (response.status == 200) { calculateResult(function(result) { If(result.status == OK) { loadFile(function(res) { If(res == success) { doSomthing(); } else { alert(“file error”) } } } else { alert(calculation error”) } } else { alert(“API error”) } } }
Promises
Promises
Promise is a javascript object that is used fordeferred and asynchronous computations. APromise represents an operation that hasn'tcompleted yet, but is expected in the future.
Promises is a pattern that exists in the webdevelopment for a long time. You can �nd it in Q orin JQuery deffered, and more.
In ECMA6 (ES2016), it has become a of�cially apart of javascript. The standard for JavaScriptPromises is called Promises/A+.
Creation of a promise:
var promise = new Promise(function(resolve, reject) { doTheWork(); if (response == success) { resolve(response); } else { reject(response) }
Usage of a promise
promise.then(function(result){ alert("success"); }, function(result) { alert("failed"); })
So much cleaner!
Promises states
pending: initial state, not ful�lled or rejected.
ful�lled: meaning that the operation completedsuccessfully.
rejected: meaning that the operation failed.
It can only succeed ones or rejected once.
Cascading and multiplicity
Another great feature of Promise is cascading.Promise enables to connect promises one after theother.
promise.then(function(result){ // success }, function(result) { //failure }).then(..).then(...).
Error handling
promise.then(..).then(..).then(...).catch(...)
multiple promises
Promise.all([promise1, promise2, promise3] ) .then(function(results){ })
Async/Await
Async/Await
ES7 Async new feature
Write asynchronous as synchronous
async function foo() { let x = await doWork(); console.log(x); }
Async/Await Error Handling
Just like synchronous code
async function foo() { try { let x = await doWork(); console.log(x); } catch (err) { console.log(err); } }
Web Workers
Web workers
Allows running a code in the background.
The code actually runs on a separate threadallowing true concurrency.
Useful for running long scripts without blockingthe application.
Web workers restrictions: -- Not being allowed to access the DOM. -- Communicate with one another by messaging.
Web workers on practice
Creating a worker:
var worker = new Worker("worker.js");
Activate it by sending it messages:
worker.postMessage(“DoSomething!”);
The worker code:
onmessage = function (e) { var response = doMyWork(e.data); // response back to caller postMessage(response);}
Registration to the worker:
worker.onmessage(function (e) { var message = e.data alert(“worker says: “ + message); }
Like promises, the worker enables to get an error:
worker.onerror = function(e) { var error= e.data alert(“worker had an error: “ + error); }
Worker termination
There are two ways to terminate a worker, frominside:
close();
Or from the creator of the worker:
worker.close();
Thank You@AmitaiBarnea
https://github.com/amitai10/js-async-examples