How to use promises
Understand promise states
A promise starts pending and later becomes fulfilled with a value or rejected with a reason. Settlement happens only once.
const delay = milliseconds => new Promise(resolve => {
setTimeout(resolve, milliseconds);
});
delay(200).then(() => console.log("Finished"));
Chain asynchronous work
Return values and promises from then callbacks so the next step receives them. End with catch for rejection.
Promise.resolve(5)
.then(number => number * 2)
.then(result => console.log(result))
.catch(error => console.error(error));
Use async and await
An async function always returns a promise. await pauses that function—not the whole program—until settlement.
async function run() {
await delay(100);
return "Ready";
}
run().then(console.log);
Handle failures with try/catch
Wrap awaited operations that may reject. Preserve useful error context and decide whether to recover or rethrow.
async function loadValue() {
try {
const value = await Promise.reject(new Error("Unavailable"));
return value;
} catch (error) {
console.error("Could not load:", error.message);
return null;
}
}
loadValue();