Creating Promises
Creating a new Promise
Sample code to create a promise:
let promise = new Promise((resolve, reject) => {
//do stuff
let isSuccessful = true;
if (isSuccessful) { /*if everything is successful*/
resolve("Success!");
}
else { /*if something went wrong*/
reject(Error("Failure."));
}
});
new Promise()
The new Promise() constructor is called to create a new promise. The constructor takes in a callback function with the arguments resolve and reject.
let promise = new Promise((resolve, reject) => {
});
Resolve()
The resolve() function is used to change the status of the promise from pending to fulfilled. The value that is passed inside the resolve() function becomes the fulfillment value of the promise.
Once the resolve() function is called, future resolve() and reject() calls no longer have any effect.
Notice how the resolve() method is used to set the fulfillment value of the promise:
resolve("Success!"); //"Success" is set as the fulfillment value of the promise
Reject()
The reject() function is used to change the status of the promise from pending to rejected. The value that is passed inside the reject() function becomes the rejection value of the promise.
Once the reject() function is called, future resolve() and reject() calls no longer have any effect.
The resolve() function can take in any object as an argument, but one common practice is to pass in a Error object because it provides a more detailed error report.
Notice how a reject() is used to send an Error object as its reject value:
reject(Error("failure")); //rejection value becomes an Error object
Promise.resolve() and Promise.reject()
Promise.resolve() is used to return a promise that is already fulfilled. Likewise, the Promise.reject() method may be used to return an already rejected promise. Both of these methods can be called outside of the new Promise() constructor.
Notice how the Promise.resolve() method is used to create an already fulfilled promise:
//A resolved promise with fulfillment value "already resolved"
let resolvedPromise = Promise.resolve("already resolved");
Notice how the Promise.reject() method is used to create an already rejected promise:
//A rejected promise with rejected value "already rejected"
let rejectedPromise = Promise.reject("already rejected");
Resolving another Promise
If another promise is passed in as an argument to resolve() then the new promise takes the fulfillment value of the passed in promise.
Notice how resolve() handles another Promise as an argument:
let firstPromise = Promise.resolve("already resolved");
//fullfillment value of secondPromise is "already resolved"
let secondPromise = Promise.resolve(firstPromise);