asynchronous development in javascript

25
Asynchronous development in JavaScript

Upload: amitai-barnea

Post on 12-Apr-2017

152 views

Category:

Software


0 download

TRANSCRIPT

Page 1: Asynchronous development  in JavaScript

Asynchronous developmentin JavaScript

Page 2: Asynchronous development  in JavaScript

Why?

Performance

responsiveness

When?

Long running operations

Calculation

Network

File access

Page 3: Asynchronous development  in JavaScript

JavaScript vs Other Languages

C++, Java, C# -- Multiple threads

JavaScript -- Single threaded -- Uses event driven programming model

Page 4: Asynchronous development  in JavaScript

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.

Page 5: Asynchronous development  in JavaScript

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.

Page 6: Asynchronous development  in JavaScript

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.

Page 7: Asynchronous development  in JavaScript

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!); });

Page 8: Asynchronous development  in JavaScript

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.

Page 9: Asynchronous development  in JavaScript

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”) } } }

Page 10: Asynchronous development  in JavaScript

Promises

Page 11: Asynchronous development  in JavaScript

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+.

Page 12: Asynchronous development  in JavaScript

Creation of a promise:

var promise = new Promise(function(resolve, reject) { doTheWork(); if (response == success) { resolve(response); } else { reject(response) }

Page 13: Asynchronous development  in JavaScript

Usage of a promise

promise.then(function(result){ alert("success"); }, function(result) { alert("failed"); })

So much cleaner!

Page 14: Asynchronous development  in JavaScript

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.

Page 15: Asynchronous development  in JavaScript

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(...).

Page 16: Asynchronous development  in JavaScript

Error handling

promise.then(..).then(..).then(...).catch(...)

multiple promises

Promise.all([promise1, promise2, promise3] ) .then(function(results){ })

Page 17: Asynchronous development  in JavaScript

Async/Await

Page 18: Asynchronous development  in JavaScript

Async/Await

ES7 Async new feature

Write asynchronous as synchronous

async function foo() { let x = await doWork(); console.log(x); }

Page 19: Asynchronous development  in JavaScript

Async/Await Error Handling

Just like synchronous code

async function foo() { try { let x = await doWork(); console.log(x); } catch (err) { console.log(err); } }

Page 20: Asynchronous development  in JavaScript

Web Workers

Page 21: Asynchronous development  in JavaScript

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.

Page 22: Asynchronous development  in JavaScript

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);}

Page 23: Asynchronous development  in JavaScript

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); }

Page 24: Asynchronous development  in JavaScript

Worker termination

There are two ways to terminate a worker, frominside:

close();

Or from the creator of the worker:

worker.close();

Page 25: Asynchronous development  in JavaScript

Thank You@AmitaiBarnea

https://github.com/amitai10/js-async-examples