Javascript Engine is synchronous

  • The core javascript V8 engine for example is synchronous
  • Nodejs and Browser adds the asynchronous functionality

JavaScript Asynchronous Programming

  • JS is single threaded, hence there is browser thread, but still there is a mechanism to run code asynchronously.

Example Async functions in JS (Browser)

  • XMLHttpRequest methods
  • Timing methods: setTimeout()
  • Animation methods: requestAnimationFrame()
  • fetch()

Callbacks

  • A function passed to some other function, which we assume will be invoked at some point
  • The function “call backs” invoking the function you give it when it is done doing its work.
// signature
setTimeout(callback, delay);
 
// example
console.log("Hi!");
 
setTimeout(function() {
    console.log("Asynchronous Result");
}, 5000);
 
console.log("Synchronous Result");
  • Here we have used an anonymous function in the callback
  • Callbacks can also be used synchronously but it is useful in async code

Error-First Callback

  • callback takes error object as the first parameter
const callback = function(err, data) {
	// call back body
}

Promises

promise
    .then(function(result) {
        // do something with result
        return(newResult)
    })
    .catch(function(error) {
        // deal with error
    })
    .finally(function() {
        // runs after promise is fulfilled or rejected
    });

Async-Await

  • async and await are just syntactical sugar on promises
  • code with async-await can be transpiled to Promises using Babel
  • async before a function mean that the function will always return a promise
  • function does not become a promise itself
async function f() {
	return 1; // returns a value, will be wrapped in promise
}
async function f2() {
	return Promise.resolve(2); // returns a promise
}
f().then(res => console.log(res)); // 1
f2().then(res => console.log(res)); // 2

More Examples of Async Functionality in Browser

Web Worker

It enables you to write code that will be executed in its own thread on the processor separate from the browser thread.

Service Worker

  • A service worker runs in a separate thread
  • Like Web Worker It can run the code and send the response back
  • Optimized to make network requests, monitor responses, and work with those reponses all in background

WebSockets

  • It maintains a persistent connection to the server and listens for updates

AJAX, XMLHTTPRequest, fetch