Syntax
new Promise((resolve, reject) => { })
promise.then(onSuccess).catch(onError)Examples
Creating and Using a Promise
Wrapping an asynchronous operation in a Promise.
function fetchUserData(userId) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (userId > 0) {
resolve({ id: userId, name: "Alice" });
} else {
reject(new Error("Invalid user ID"));
}
}, 1000);
});
}
fetchUserData(1)
.then(user => console.log(user))
.catch(error => console.log(error.message));Chaining Promises
Each then() returns a new promise, allowing sequential operations.
fetch("/api/user/1")
.then(response => response.json())
.then(user => {
console.log("User:", user.name);
return fetch(`/api/posts/${user.id}`);
})
.then(response => response.json())
.then(posts => console.log("Posts:", posts))
.catch(error => console.log("Something failed:", error.message))
.finally(() => console.log("Request cycle complete"));Best practices
- Always add a .catch() to handle rejected promises - an unhandled rejection can silently fail or crash depending on the environment
- Return a value or another promise from inside .then() when chaining, so the next .then() receives the right data
- Prefer async/await over long .then() chains in most cases - it reads more like familiar synchronous code
- Use .finally() for cleanup logic (hiding a spinner, closing a connection) that should run whether the promise succeeds or fails
Runtime & versions
Browsers and JavaScript runtimes. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
ECMAScript specification