Asynchronous development in 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 mouse events, keyboard events DOM events, etc. The event is queued into the event loop. Each time, the JavaScript thread takes the next event and execute it. When it nish to handle the event, it takes the next one.
JavaScript does one thing at a time? The browser expose a set of asynchronous functionalities. The commons are network operation such as HTTP 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 execute the attached functionality.
Callback Asynchronous objects allow to attach a callback to the execution of the function. The callback is a function that will be called as the operation 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 of problem: Assuming we need to do a series of operations. Each operation depends on the success of its previous. The code can become messy. Reviewing, debugging and xing the code had become 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 for deferred and asynchronous computations. A Promise represents an operation that hasn't completed yet, but is expected in the future. Promises is a pattern that exists in the web development for a long time. You can nd it in Q or in JQuery deffered, and more. In ECMA6 (ES2016), it has become a of cially a part of javascript. The standard for JavaScript Promises 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 completed successfully. 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 the other. 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 thread allowing true concurrency. Useful for running long scripts without blocking the 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, from inside: close(); Or from the creator of the worker: worker.close();
Thank You @AmitaiBarnea https://github.com/amitai10/js-async-examples

Asynchronous development in JavaScript

  • 1.
  • 2.
  • 3.
    JavaScript vs OtherLanguages C++, Java, C# -- Multiple threads JavaScript -- Single threaded -- Uses event driven programming model
  • 4.
    The Event Loop Theweb browser trigger events, such as mouse events, keyboard events DOM events, etc. The event is queued into the event loop. Each time, the JavaScript thread takes the next event and execute it. When it nish to handle the event, it takes the next one.
  • 5.
    JavaScript does onething at a time? The browser expose a set of asynchronous functionalities. The commons are network operation such as HTTP 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 execute the attached functionality.
  • 6.
    Callback Asynchronous objects allowto attach a callback to the execution of the function. The callback is a function that will be called as the operation ended.
  • 7.
    Implementation of acallback 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!); });
  • 8.
    Callback hell Using callbackscan caused a different type of problem: Assuming we need to do a series of operations. Each operation depends on the success of its previous. The code can become messy. Reviewing, debugging and xing the code had become a very hard thing to do.
  • 9.
    Our code willlook 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”) } } }
  • 10.
  • 11.
    Promises Promise is ajavascript object that is used for deferred and asynchronous computations. A Promise represents an operation that hasn't completed yet, but is expected in the future. Promises is a pattern that exists in the web development for a long time. You can nd it in Q or in JQuery deffered, and more. In ECMA6 (ES2016), it has become a of cially a part of javascript. The standard for JavaScript Promises is called Promises/A+.
  • 12.
    Creation of apromise: var promise = new Promise(function(resolve, reject) { doTheWork(); if (response == success) { resolve(response); } else { reject(response) }
  • 13.
    Usage of apromise promise.then(function(result){ alert("success"); }, function(result) { alert("failed"); }) So much cleaner!
  • 14.
    Promises states pending: initialstate, not ful lled or rejected. ful lled: meaning that the operation completed successfully. rejected: meaning that the operation failed. It can only succeed ones or rejected once.
  • 15.
    Cascading and multiplicity Anothergreat feature of Promise is cascading. Promise enables to connect promises one after the other. promise.then(function(result){ // success }, function(result) { //failure }).then(..).then(...).
  • 16.
  • 17.
  • 18.
    Async/Await ES7 Async newfeature Write asynchronous as synchronous async function foo() { let x = await doWork(); console.log(x); }
  • 19.
    Async/Await Error Handling Justlike synchronous code async function foo() { try { let x = await doWork(); console.log(x); } catch (err) { console.log(err); } }
  • 20.
  • 21.
    Web workers Allows runninga code in the background. The code actually runs on a separate thread allowing true concurrency. Useful for running long scripts without blocking the application. Web workers restrictions: -- Not being allowed to access the DOM. -- Communicate with one another by messaging.
  • 22.
    Web workers onpractice 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);}
  • 23.
    Registration to theworker: 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); }
  • 24.
    Worker termination There aretwo ways to terminate a worker, from inside: close(); Or from the creator of the worker: worker.close();
  • 25.