Asynchronous Javascript

Özgün Bal

Contents

  • Why async?
  • Asynchronous behavior in JS
  • Callback vs Promise
  • Promise
  • Generator
  • Async/await
  • Observables
  • References

Why async?

  • non-blocking execution
  • more performant/efficient
  • many modern languages have async logic
  • handling for long processes

Asynchronous Behavior

  • Event Loop /Queue
  • Provides non-blocking execution

Title Text

Callbacks

  • A function for future call
  • Causes callback hell
  • Can be called to early
  • Can be not called
  • Can be called few or many times
  • Fail to pass along any necessary parameters
  • Swallow error/exceptions

Promises

  • Native type for future value
  • More structured way yo handle asynchronous job

Solves these

Callback Hell

Promise

Promise syntax

  • Called with new to create one
  • Takes a function with two parameters
  • One for fulfillment, one for rejection of the desired task
  • Return a Promise object immediately
  • Not mutated, resolved once
  • Acquiring the value is done by .then()
const promise = new Promise(function(resolve, reject){
  if (satisfiedCondition) {
    resolve('Task is done');
  } else {
    reject('Error occured');
  }
})

promise.then(function(data){
  console.log(data) // prints 'Task is done' when promise is resolved
}).catch(function(error){
  console.log(error) // prints 'Error occured' when promise is rejected
})

Promise advantages

  • Can be called only once
  • resolve() and reject() takes only one parameter
  • Unhandled errors cause rejection
  • Always asynchronous even with immediately resolved ones

Promise methods

  • Promise.resolve()
  • Promise.reject()
  • Promise.all()
  • Promise.race()
  • Promise.allSettled()
  • Promise.any()
// Immediately resolved promise object
const resolved = Promise.resolve(5);

// Immediately rejected promise object
const rejected = Promise.reject('Oops');

// Takes array of promises and resolves if all of them resolved otherwise rejects
const allFulfilled = Promise.all([resolved, rejected]);

// Returns first resolved/rejected promise in array of promises
const raceOfPromises = Promise.race(promiseArray);

// // Takes array of promises and resolves when all of them either fulfilled or rejected
const allSettled = Promise.allSettled(promiseArray);

// Returns first fullfiled promise in array of promises
const anyFulfilled = Promise.any(promiseArray);

Generators

  • yield keyword
  • python has also generators
  • Pausing execution of function
  • Increase iteration capabilities

Async/Await

  • Promise  + generator
  • Looks like sync but async
  • Better and readable code
  • Uses new words: async and await
  • ES7 feature

Observables

import { Observable } from 'rxjs';
 
const foo = new Observable(subscriber => {
  console.log('Hello');
  subscriber.next(42);
});
 
foo.subscribe(x => {
  console.log(x);  // Hello \n 42
});
foo.subscribe(y => {
  console.log(y);  // Hello \n 42
});

References

  • Kyle Simpson - You Don't Know Javascript
  • Udacity - Intermediate Javascript Nanodegree
  • MDN
  • RxJS

Any questions?

Thank you for listening

Asynchronous Javascript

By Özgün Bal

Asynchronous Javascript

  • 101