A JavaScript Promise is a way to handle tasks that take time to complete, like fetching data from the internet. A Promise can be in one of three states: pending (still working), fulfilled (finished successfully), or rejected (something went wrong).
const promise = new Promise((resolve, reject) => { const success = true; if (success) { resolve('Task completed successfully!'); } else { reject('Task failed!'); } }); promise.then( result => console.log(result), error => console.error(error) );
When something goes wrong with a Promise, it moves into the 'rejected' state. The .catch() method lets you handle these errors gracefully.
const promise = new Promise((resolve, reject) => { setTimeout(() => { reject('Promise failed after 1 second'); }, 1000); }); promise .then(result => console.log(result)) .catch(error => console.error(error));
If you have several tasks to complete at the same time, Promise.all() lets you run them together and waits for all to finish before moving on.
const promise1 = new Promise(resolve => setTimeout(resolve, 300, 'Task 1 done')); const promise2 = new Promise(resolve => setTimeout(resolve, 200, 'Task 2 done')); Promise.all([promise1, promise2]).then(results => { console.log(results[0]); // 'Task 1 done' console.log(results[1]); // 'Task 2 done' });
You can create a Promise by using a function that takes two arguments: resolve (to mark it as successful) and reject (to mark it as failed).
const promise = new Promise((resolve, reject) => { resolve('This promise was successful!'); });
After a Promise is resolved, you can use the .then() method to run additional code. If the Promise fails, you can handle the error with .catch().
const promise = new Promise((resolve, reject) => { setTimeout(() => resolve('Promise resolved successfully'), 200); }); promise .then(result => console.log(result)) .catch(error => console.error(error));
To keep your code neat and easy to read, you can chain multiple .then() methods instead of nesting them inside each other.
const promise = new Promise((resolve) => { setTimeout(() => resolve('**'), 1000); }); promise .then(stars => stars + stars) .then(doubledStars => doubledStars + '!') .then(result => console.log(result));
A Promise object represents a task that hasn’t finished yet but will eventually. You can use .then() to get the result when it's ready or .catch() to deal with any problems.
const promise = new Promise(resolve => setTimeout(() => resolve('Hello'), 100)); promise.then(result => { return result === 'Hello' ? 'Hi there!' : 'Who are you?'; }).then(response => console.log(response));
An async function in JavaScript is a special type of function that always returns a Promise. It lets you write code that looks like it runs one step at a time, even though some steps might take a while.
async function greet() { return 'Hello!'; } greet().then(message => console.log(message));
The await keyword can only be used inside async functions. It makes JavaScript wait until a Promise is done before moving on, making your code easier to follow.
async function getMessage() { const message = await new Promise(resolve => setTimeout(() => resolve('Hello after 2 seconds'), 2000)); console.log(message); } getMessage();
You can run multiple Promises at the same time using async and await, and then wait for all of them to finish before continuing.
async function runPromises() { const promise1 = Promise.resolve(5); const promise2 = 44; const promise3 = new Promise(resolve => setTimeout(() => resolve('Done!'), 100)); const results = await Promise.all([promise1, promise2, promise3]); console.log(results); // [5, 44, 'Done!'] } runPromises();
You can handle errors in async functions using try...catch blocks, making your code easier to read and understand.
async function fetchData() { try { const response = await fetch('https://jsonplaceholder.typicode.com/todos/1'); const data = await response.json(); console.log(data); } catch (error) { console.error('Error fetching data:', error); } } fetchData();
The async-await syntax lets you write asynchronous code that looks like it runs step by step, making it easier to write and maintain.
async function showMessage() { const message = await new Promise(resolve => setTimeout(() => resolve('Hello, World!'), 2000)); console.log(message); } showMessage();
Welcome to our comprehensive collection of programming language cheatsheets! Whether you're a seasoned developer or a beginner, these quick reference guides provide essential tips and key information for all major languages. They focus on core concepts, commands, and functions—designed to enhance your efficiency and productivity.
ManageEngine Site24x7, a leading IT monitoring and observability platform, is committed to equipping developers and IT professionals with the tools and insights needed to excel in their fields.
Monitor your IT infrastructure effortlessly with Site24x7 and get comprehensive insights and ensure smooth operations with 24/7 monitoring.
Sign up now!