Skip to the content.

Asynchronous Coding

javascript.into -> Promises, async/await


error-first callback style
// callback where err will be null if successful
callback(err, result);

// used like
loadScript('/my/script.js', function(error, result) {
  if (error) {
    // handle error
  } else {
    // script loaded successfully - result has a value
Callback hell or pyramid of doom

The style with callbacks in callbacks, leads to deeply nested structures.

It can be unwrapped by making each level into its own function.


let promise = new Promise(function(resolve, reject) {
  // executor (the producing code)
  // if it succeeds it should call
  // if it fails it should call
  reject(new Error(..));

The promise object returned by the new Promise constructor has these internal properties:

A promise that is either fulfilled or rejected is called settled, as opposed to an initially pending promise.

The state and result are internal

The properties state and result of the Promise object are internal. They can not be accessed, but the promise methods .then / .catch / .finally are used for that.

Promise.all(iterable), etc.