Async JavaScript

Intro

JavaScript is a single-threaded synchronous environment. That means that it can only do one thing with a single processor at a time. Anythign that takes a substantial amount of time needs to be run asynchronously, or multiple processes at the same time. If they weren’t asynchronous, the entire process would be stalled until the thing that takes time is finished. For example:

There are a few ways to do asynchronous JavaScript:

// With standard functions
setTimeout(function() { // This function is a callback
  doSomething();
}, 5000);

// With an arrow function
setTimeout(() => {
  doSomething();
}, 5000);

Callbacks can also pass arguments to the callback function: Note: Make sure you know what arguments are passed by your callback.

function sumAsync(number1, number2, callback) {
  setTimeout(function() {
      var response = number1 + number2;
      callback(null, response);
  }, 5000)
}
// Why did I pass null as the first argument of my function? Usually, callbacks are in the shape of function(error, response){}. That's why you need to be aware of what your callback returns.

sumAsync(1, 2, function(error, response) {
  console.log(response);
})

fetch('https://www.anapi.com')
.then(function(response){
  // We have to process the response with Fetch
  return response.json();
}).then(function(json){
  doSomethingWithJson(json);
});

Suggested Learning

Requirements

Extra Learning

This list is by no means complete. Feel free to add an issue or put in a pull request to update it.