Table of Contents

About

This page is about Asynchrony in javascript.

Asynchrony is not only critical to the performance of our applications, but it’s also increasingly becoming the critical factor in writability and maintainability.

Javascript knowns 2 asynchronous method:

Example

Fetch operations are asynchronous by nature and returns generally a promise. See Browser - Fetching Resources (Request/Response).

Event loop

Javascript is single threaded, whenever you use an asynchronous method (callback, async/promise) in javascript, it gets put into a queue, called by the event loop, and gets executed there.

Method

Callback

callbacks is the primary method of enabling asynchrony.

Callback pyramid of doom

// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises
doSomething(function(result) {
  doSomethingElse(result, function(newResult) {
    doThirdThing(newResult, function(finalResult) {
      console.log('Got the final result: ' + finalResult);
    }, failureCallback);
  }, failureCallback);
}, failureCallback);

getData( a => {
     getMoreData(a, b => {
         getMoreData(b, c => {
             getMoreData(c, d => {
                 getMoreData(d, e => {
                     console.log(e);
                 }
             }
         }
     }
}

Promise

The promise function has two syntax:

Documentation / Reference