What are Promises and how do they work?
TL;DR
Promises in JavaScript are objects that represent the eventual completion (or failure) of an asynchronous operation and its resulting value. They have three states: pending
, fulfilled
, and rejected
. You can handle the results of a promise using the .then()
method for success and the .catch()
method for errors.
let promise = new Promise((resolve, reject) => {// asynchronous operationconst success = true;if (success) {resolve('Success!');} else {reject('Error!');}});promise.then((result) => {console.log(result); // 'Success!' (this will print)}).catch((error) => {console.error(error); // 'Error!'});
What are Promises and how do they work?
Definition
Promises are a way to handle asynchronous operations in JavaScript. They provide a cleaner, more readable way to handle asynchronous code compared to traditional callback functions.
States of a Promise
A promise can be in one of three states:
Pending
: The initial state, neither fulfilled nor rejected.Fulfilled
: The operation completed successfully.Rejected
: The operation failed.
Creating a Promise
You create a promise using the Promise
constructor, which takes a function with two arguments: resolve
and reject
. These are callbacks that you call to change the state of the promise.
let promise = new Promise((resolve, reject) => {// asynchronous operationconst success = true;if (success) {resolve('Success!');} else {reject('Error!');}});
Handling a Promise
To handle the result of a promise, you use the .then()
method for a successful outcome and the .catch()
method for an error.
let promise = new Promise((resolve, reject) => {// asynchronous operationconst success = false;if (success) {resolve('Success!');} else {reject('Error!');}});promise.then((result) => {console.log(result); // 'Success!'}).catch((error) => {console.error(error); // 'Error!' (this will print)});
Chaining Promises
Promises can be chained to handle multiple asynchronous operations in sequence. Each .then()
returns a new promise, allowing for further chaining.
new Promise((resolve, reject) => {setTimeout(() => {resolve('Promise 1 resolved after 1 second');}, 1000);}).then((result) => {console.log(result);return 'Another promise';}).then((anotherResult) => {console.log(anotherResult);}).catch((error) => {console.error(error);});
Combining Promises
You can use Promise.all()
to run multiple promises in parallel and wait for all of them to complete.
let promise1 = Promise.resolve('First');let promise2 = Promise.resolve('Second');let promise3 = new Promise((resolve, reject) => {setTimeout(() => {resolve('Third');}, 2000);});Promise.all([promise1, promise2, promise3]).then((results) => {console.log(results); // ['First', 'Second', 'Third']});
In the above example, while promise1
and promise2
resolve instantly, Promise.all
waits for promise3
, which takes 2 seconds, before logging the results.