A Promise represents a value available now, later, or never.
const p = new Promise((resolve) => {
setTimeout(() => resolve(123), 10);
});
p.then((v) => console.log("resolved:", v));Handling errors:
Promise.reject(new Error("boom"))
.then(() => {
// skipped
})
.catch((err) => {
console.error("caught:", err.message);
});Common helpers:
Promise.all(fails fast)Promise.allSettledPromise.racePromise.any
fetch is available in modern browsers and Node 18+.
const res = await fetch("https://jsonplaceholder.typicode.com/todos/1");
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const data = await res.json();
console.log(data);async functions return Promises. await pauses within the async function.
async function getTodo(id) {
const res = await fetch(`https://jsonplaceholder.typicode.com/todos/${id}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
}
getTodo(1)
.then((todo) => console.log(todo.title))
.catch((err) => console.error(err));Try/catch with async:
async function main() {
try {
const todo = await getTodo(1);
console.log(todo);
} catch (err) {
console.error("failed:", err.message);
}
}
main();