Skip to content

Instantly share code, notes, and snippets.

@boly38
Last active March 18, 2025 12:16
Show Gist options
  • Save boly38/4c9d0923ab6eabb5f98954a29fb37e62 to your computer and use it in GitHub Desktop.
Save boly38/4c9d0923ab6eabb5f98954a29fb37e62 to your computer and use it in GitHub Desktop.
NodeJS, Promise and "throw"
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
function promiseMethod() {
return Promise.resolve("ok");
}
function good_sync_example() {
return new Promise((resolve, reject) => {
throw new Error("Err... no async and that's fine for throw management by Promise");
});
}
async function good_async_example() {
await sleep(100);
throw new Error("Err...");
}
async function bad_example1_fixed() {
return new Promise(async (resolve, reject) => {
try {
await sleep(100);
throw new Error("Err... ");
} catch (e) {
reject(e);
}
});
}
function example3WithAsyncPromiseResultThrow() {
return new Promise(async (resolve, reject) => {
promiseMethod()
.then(async res => {
await sleep(100);
throw new Error(`oops was ${res} but..`);
})
.catch(err =>{
console.log(`ex3: ${err.message}`);
reject(err);
});
});
}
function bad_async_example1() {
return new Promise(async (resolve, reject) => {
await sleep(100);
throw new Error("Err... Promise 'async' prevents throw management :(");
});
}
console.log(`# good_sync_example`)
await good_sync_example().catch(err => console.log(`>>>${err.message}`));
console.log(`# good_async_example`)
await good_async_example().catch(err => console.log(`>>>${err.message}`));
console.log(`# bad_example1_fixed`)
await bad_example1_fixed().catch(err => console.log(`>>>${err.message}`));
console.log(`# example3WithAsyncPromiseResultThrow`)
await example3WithAsyncPromiseResultThrow().catch(err => console.log(`>>>${err.message}`));
console.log(`# bad_async_example1`)
await bad_example1().catch(err => console.log(`>>${err.message}`));
console.log(`# end`)
// node --unhandled-rejections=strict promise_throw_draft.js
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment