Last active
February 6, 2019 22:25
-
-
Save upphiminn/7b7359462f32589867334d88999b716f to your computer and use it in GitHub Desktop.
err...
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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