Skip to content

Instantly share code, notes, and snippets.

@upphiminn
Last active February 6, 2019 22:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save upphiminn/7b7359462f32589867334d88999b716f to your computer and use it in GitHub Desktop.
Save upphiminn/7b7359462f32589867334d88999b716f to your computer and use it in GitHub Desktop.
err...
async function doSomething() {
return new Promise((resolve, reject) => {
setTimeout(() => resolve("done!"), 1000)
});
}
// Rejection case
async function doSomethingBad() {
return new Promise((resolve, reject) => {
setTimeout(() => reject("crap!"), 1000)
});
}
// Exception case
async function throwSomethingBad() {
return window.test.test;
}
async function makeItNice(fn) {
let result = null;
let error = null;
try {
result = await fn()
} catch(e) {
error = e;
}
return [result, error];
}
async function test() {
// REJECT CASE
/* let [result, error] = await makeItNice(doSomethingBad) */;
// THROW CASE
/* let [result, error] = await makeItNice(throwSomethingBad) */;
// HAPPY CASE
let [result, error] = await makeItNice(doSomething);
if (error) {
if (!error.name) {
console.log('Err... promise rejected');
} else {
console.log("it's a real exception!", error.name);
// bla bla
// error.name doesn't exist on rejected promises
// ... unless you reject with an object with a name property ofc:D
}
return;
}
if (result) {
console.log('Works!', result);
}
}
test();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment