Promises in JavaScript
May 09, 2020Promises are enhanced versions of callback functions.
Syntax of Promise:
let promise = new Promise(function(resolve, reject) {
// executor (the producing code, "singer")
});
Promise function takes one more function which is called as Executor which is taking two paramters, and both of them are callbacks:
- resolve: This callback is returned when asynchronous task has successfully completed.
- reject: This callback is returned when async. task has failed to execute.
Internal Properties of Promises:
The promise object returned by the new Promise
constructor has two internal properties:
- state : initially “pending”, then changes to either “fulfilled” when resolve is called or “rejected” when reject is called.
- result : initially undefined, then changes to value when resolve(value) called or error when reject(error) is called.
Example of performing some asynchronous task with the help of promise:
let promise = new Promise(function(resolve, reject) {
// the function is executed automatically when the promise is constructed
// after 1 second signal that the job is done with the result "done"
setTimeout(() => resolve("done"), 1000);
});
In above example we are returning resolve callback with the message done after one second using setTimeout()
. Which means our promise has performed task successfully.
Now for sending error in case task has failed, you can write:
let promise = new Promise(function(resolve, reject) {
// after 1 second signal that the job is finished with an error
setTimeout(() => reject(new Error("Whoops!")), 1000);
});
After one second, above promise is returning the error saying Whoops!.
Consumer Methods:
There are three methods which can be used on promise:
- then: This method is used for fetching the result from the promise when the task will be completed. Example:
let promise = new Promise(function(resolve, reject) {
setTimeout(() => resolve("done!"), 1000);
});
// resolve runs the first function in .then
promise.then(
result => alert(result), // shows "done!" after 1 second
error => alert(error) // doesn't run
);
- catch: This method is used for fetching the error if promise fails to perform task.
Example:
let promise = new Promise((resolve, reject) => {
setTimeout(() => reject(new Error("Whoops!")), 1000);
});
// .catch(f) is the same as promise.then(null, f)
promise.catch(alert);
- finally: It is similar like
try{} catch{}
. We use it for cleanup operations. It will always execute no matter promise is successful or failed.
Example:
new Promise((resolve, reject) => {
setTimeout(() => resolve("result"), 2000)
})
.finally(() => alert("Promise ready"))
.then(result => alert(result));