Asynchronous Javascript

Javascript is synchronous by default i.e. every function call is blocking the next. Every line is executed in sequence.

If you want to execute code asynchronously (concurrently) you have to use a special Promise object. A promise can be seen as chunk of code that will produce a final result in the future.

A promise object is created from a function which have two parameters, resolve and reject, which themselves are functions.

f(resolve, reject)

The function,f, contain the code that is to be executed by the promise and the parameters can be used to exit from f with a successful result or a failed result.

Here is an example where a promise is created.

let myPromise = new Promise(function(myResolve, myReject) {
  console.log("this is the code executed in promise")
  success = another_func();
  if (success) {
	  myResolve("this worked out fine"); 
  } else {
	  myReject("promise failed"); 
  }
});

The resolve and reject functions are used (from within the promise function) to report if execution was successful or not.

If code creating the promise need to handle the result from a promise you can add handlers using the then() function on the promise.

myPromise.then(
  function(value) { /* code to handle resulting value if successful */ },
  function(error) { /* code to handle error */ }
);

The resolve and reject function parameters are optional and may be left out if not needed.

let myPromise2 = new Promise(function() {
  console.log("this is the code executed in promise")
});

Note that promises are executed even if results are not handled by the then() function.

Promises are executed concurrently by default, but may be waited for (blocking) as well by prepending an await call before promise.

The only additional requirement is that a function that is blocking on a promise must be marked by an async marker.

async function thatBlockOnPromise() {
  await new Promise(function() {
    console.log("this is the code executed in promise")
  });  // block on this line until promise complete
}
thatBlockOnPromise();   // this line executes asynchronously
console.log("this code may execute after code in promise")

Functions marked by async will always return a promise. This means that async functions are also executed asynchronously (non-blocking).

If the return value of an async function is not explicitly a promise, its regular return value will be implicitly wrapped in a promise.