Promise is an object that can be used to get the outcome of an asynchronous operation when that result is not instantly available.
Promise object can be in one of three states:
While the value is not yet available, the
Promise stays in the
pending state. Afterwards, it transitions to one of the two states:
A resolved promise stands for a successful completion. Due to errors, the promise may go in the
In the given code block, if the
Promise is on
resolved state, the first parameter holding a callback function of the
then() method will print the resolved value. Otherwise, an alert will be shown.
Promise object is created using the
The constructor of the
Promise object takes a function, known as the executor function, as the argument. This function is responsible for resolving or rejecting the promise.
Promise object may use any one or both of them inside its executor function.
In the given example, the promise is always resolved unconditionally by the
resolve function. The
reject function could be used for a rejection.
Promise object can be used to get the eventual result (or error) of the asynchronous operation.
.then() accepts two function arguments. The first handler supplied to it will be called if the promise is resolved. The second one will be called if the promise is rejected.
Chaining multiple .then() methods
.then() method returns a Promise, even if one or both of the handler functions are absent. Because of this, multiple
.then() methods can be chained together. This is known as composition.
In the code block, a couple of
.then() methods are chained together. Each method deals with the resolved value of their respective promises.
.catch() method for handling rejection
The function passed as the second argument to a
.catch() method of the promise object. The information for the rejection is available to the handler supplied in the
.then() methods. This is better practice than nesting.
Chaining helps streamline the development process because it makes the code more readable and easier to debug.
Promise.all() method can be used to execute multiple promises in parallel. The function accepts an array of promises as an argument. If all of the promises in the argument are resolved, the promise returned from
Promise.all() will resolve to an array containing the resolved values of all the promises in the order of the initial array. Any rejection from the list of promises will cause the greater promise to be rejected.
In the code block,
2 will be printed respectively even though
promise1 will be resolved after