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.
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.
The solution in JavaScript is a Promise.
Let’s examine how a promise is created:
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.