A Promise in JavaScript represents a value that may be available now, or in the future, or never. Promises are used to handle asynchronous operations like reading files, making HTTP requests, etc. It allows you to attach callbacks to handle success or failure.
A promise can be in one of three states:
To create a promise, use the new Promise()
constructor. Here's how it works:
// Creating a new Promise let myPromise = new Promise(function(resolve, reject) { let success = true; if (success) { resolve("The operation was successful!"); } else { reject("The operation failed."); } }); myPromise.then(function(result) { console.log(result); // "The operation was successful!" }).catch(function(error) { console.log(error); // "The operation failed." });
Promises can be chained together. Each then()
method returns a new promise, allowing multiple actions to occur in sequence.
let promiseChain = new Promise(function(resolve, reject) { resolve(10); }); promiseChain.then(function(result) { console.log(result); // 10 return result * 2; // Returning a new value for the next .then() }).then(function(result) { console.log(result); // 20 }).catch(function(error) { console.log(error); });
In some cases, you may want to wait for multiple promises to resolve or race against them. JavaScript provides two handy methods:
let promise1 = new Promise(function(resolve) { setTimeout(resolve, 1000, "One"); }); let promise2 = new Promise(function(resolve) { setTimeout(resolve, 500, "Two"); }); Promise.all([promise1, promise2]).then(function(values) { console.log(values); // ["One", "Two"] }); Promise.race([promise1, promise2]).then(function(value) { console.log(value); // "Two" (The first to resolve) });
Promises are ideal for handling multiple asynchronous operations. Hereβs an example where you perform multiple async operations and use Promise.all()
to wait for all of them to complete:
function fetchData(url) { return new Promise(function(resolve) { setTimeout(function() { resolve(`Data fetched from ${url}`); }, 1000); }); } let api1 = fetchData("https://api1.com"); let api2 = fetchData("https://api2.com"); Promise.all([api1, api2]).then(function(results) { console.log(results); // ["Data fetched from https://api1.com", "Data fetched from https://api2.com"] });
You can handle errors in promises using the catch()
method, which catches any rejected promise or error thrown:
let errorPromise = new Promise(function(resolve, reject) { reject("Something went wrong!"); }); errorPromise.catch(function(error) { console.log(error); // "Something went wrong!" });
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!