Module 0324: Javascript Promises

Tak Auyeung, Ph.D.

December 13, 2018

Contents

1 About this module
2 The Concept of asynchronous operations
3 The problem
4 The solution

1 About this module

2 The Concept of asynchronous operations

The word “asynchronous” means not synchronous. In programming, this means when an event happens cannot be anticipated in software. For example, after making a request to a server, when the reply is received is asynchronous because it is not possible to predict exactly when that will happen.

There are two main approaches to handle asynchronous operations. The first one is to busy-wait until the event occurs. However, this approach also means the program cannot do anything while waiting for the anticipated event.

The second approach is to continue to process what does not depend on the response. However, this also means that we need a mechanism to pass control to some code when the event does happen. In JavaScript, one way to do this is via the use of Promises.

3 The problem

There are a few piece to the problem:

The problem is that it is important to separate the code that starts the operation from the code to handle the termination of the operation. This separation allows the abstraction of the potentially complex logic to start an operation (like formatting a REST request) into methods, while allowing flexibility to the caller of the methods to process the result of an asynchronous operation.

4 The solution

The solution in JavaScript is a Promise.

Let’s examine how a promise is created:

1let aPromise = 
2  new Promise 
3  ( 
4   (resolve, reject) =>  
5    { 
6      // start an asynchronous operation  
7      // when it succeds, call resolve 
8      // when it fails, call reject 
9    }  
10  ); 

From line 4 to line 9 is the anonymous executor function. It takes two parameters. resolve is a function to call when the operation concludes successfully, and reject is a function to call when the operation fails. After calling resolve or reject, the promise is “settled.”

This decouples the code to start an operation from the code that handles the results of an operation.

The following code examines how a Promise object is utilized once it is created.

11aPromise.then( 
12  (resolveMsg} => 
13  { 
14   // this code is chain called 
15   // when resolve in the executor function is called 
16  }, 
17  (rejectMsg) => 
18  { 
19   // this code is chain called 
20   // when reject in the executor function is called 
21  } 
22  );