JavaScript Promises
Learn to handle asynchronous operations with Promises.
1. Creating a Promise
A Promise is an object representing the eventual completion or failure of an asynchronous operation.
JavaScript Code
Live JavaScript representation with highlighted changes
const myPromise = new Promise((resolve, reject) => {// Asynchronous operation heresetTimeout(() => {if (Math.random() > 0.5) {resolve("Success!");} else {reject("Failure!");}}, 1000);});myPromise.then(result => console.log(result)).catch(error => console.error(error));
2. Chaining Promises
Promises can be chained to execute asynchronous operations in sequence.
JavaScript Code
Live JavaScript representation with highlighted changes
new Promise(resolve => resolve(1)).then(result => {console.log("Step 1:", result);return result * 2;}).then(result => {console.log("Step 2:", result);return result * 2;}).then(result => {console.log("Step 3:", result);});
3. async/await
The async/await
syntax provides a more synchronous-looking way to work with Promises.
JavaScript Code
Live JavaScript representation with highlighted changes
async function myAsyncFunction() {try {const result1 = await new Promise(resolve => setTimeout(() => resolve("First step done"), 1000));console.log(result1);const result2 = await new Promise(resolve => setTimeout(() => resolve("Second step done"), 1000));console.log(result2);} catch (error) {console.error(error);}}myAsyncFunction();
Console Output