JavaScript Promises Explained: Creation and .then()
Direct Answer & Overview
A JavaScript Promise is a proxy object representing the eventual completion or failure of an asynchronous operation and its resulting value. Promises eliminate nested callback hell with chainable .then(), .catch(), and .finally() methods.
JavaScript Source Code
const promise = Promise.resolve("Success");
promise.then(result => {
console.log(result);
});How does this JavaScript code work?
JavaScript Promises provide an abstraction over asynchronous operations. A Promise exists in one of three mutually exclusive states: pending, fulfilled (resolved with a value), or rejected (with an error reason). You attach fulfillment handlers using `.then()` and rejection handlers with `.catch()`. Handlers execute asynchronously on the JavaScript microtask queue, guaranteeing deterministic scheduling after the current synchronous execution turn completes.
What is the expected terminal output?
Executing this code in JS CodeLab produces the following stdout sequence in the developer console:
SuccessCommon mistakes to avoid
- !Forgetting to return a value or inner promise inside a .then() callback, breaking the promise chain.
- !Omitting a .catch() error handler, causing unhandled promise rejections that crash Node.js processes.
- !Falling into callback hell inside .then() blocks instead of returning promises for flat chaining.
- !Confusing asynchronous execution order with synchronous sequential execution.
Frequently Asked Questions
What are the three states of a JavaScript Promise?
A Promise is always in one of three states: pending (initial state), fulfilled (operation completed successfully), or rejected (operation failed with an error).
Can a settled Promise change its state?
No. Once a Promise is either fulfilled or rejected, its state and resulting value or error reason become permanently immutable.
What is the difference between microtasks and macrotasks?
Promise callbacks execute as microtasks, which run immediately after the current script executes and before the event loop processes macrotasks like setTimeout or I/O events.
Comprehensive Tutorial
Want an in-depth understanding of this topic?
Read our complete, interactive tutorial covering memory management, edge cases, and best practices.
Read the full promises tutorial →