Ways to Create a Promise
Learn how to create a promise and return it from an asynchronous function in one of its three states.
We'll cover the following
Asynchronous function and promise
In order to return a promise, asynchronous functions have to first create a promise. If the asynchronous function finds that the task at hand is time-consuming, it will internally hold a reference to the promise it creates and returns the promise instantaneously to its caller. Once the task is complete, it will pass the result or the error through that promise. However, if the asynchronous function can quickly complete the task at hand, it can return the promise in the resolved state instead of the pending state, making the result available to the caller right away through the promise. Likewise, if the asynchronous function finds an error in its input parameters or decides to return an error for any reason, it can return a promise in the rejected state instead of the pending state, passing the error details through the promise it returns.
Creating a promise
When writing an asynchronous function, you may create a promise in a resolved state, a rejected state, or a pending state with the intent to resolve or reject later. Let’s use these three approaches in one example.
Get hands-on with 1400+ tech skills courses.