JS Promises
9 min read
What is JS Promises?
A Promise in JavaScript represents a value that may be available now, later, or never. Promises are used for asynchronous operations like API calls. They can be in one of three states: pending, fulfilled, or rejected.
Syntax & Usage
The syntax and usage patterns for JS Promises follow standard JavaScript conventions. Below you will see code examples that demonstrate the most common use cases. Try modifying these examples in your own editor to experiment with different approaches.
Example
Here is a practical example demonstrating JS Promises:
Tips & Best Practices
- Use
constby default,letwhen you need to reassign - Use strict equality (
===) instead of loose equality (==) - Handle errors with try/catch blocks for robust code
- Use template literals instead of string concatenation
Summary
In this lesson you learned about JS Promises. Practice writing code to reinforce these concepts and move on to the next lesson when you feel comfortable.
Examples
javascript
// Using Promises
function fetchUser(id) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (id > 0) resolve({ id, name: 'Alice' });
else reject(new Error('Invalid ID'));
}, 1000);
});
}
// Using async/await
async function getUser() {
try {
const user = await fetchUser(1);
console.log(user); // { id: 1, name: 'Alice' }
} catch (error) {
console.error(error.message);
}
}
getUser();