Example 1 — reject
Failure path.
JavaScript
new Promise((_, reject) => reject(new Error("no")))
.catch((e) => console.log(e.message));How It Works
- reject with an Error.
- catch handles it.
new Promise((resolve, reject) => { ... }) runs the executor immediately. Call resolve(value) to fulfill or reject(error) to reject. Prefer async functions or existing promise-returning APIs when you can.
const p = new Promise((resolve, reject) => {
resolve("ok");
});
p.then((v) => console.log(v));Failure path.
new Promise((_, reject) => reject(new Error("no")))
.catch((e) => console.log(e.message));Classic use case.
function wait(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
console.log(typeof wait(0).then);CODETOFUN NEWS
Get the latest IT news, programming updates, and technology trends directly on your phone.
Your daily dose of tech, straight to your feed.
6 people found this page helpful