Created
December 18, 2021 03:00
-
-
Save foozlevazquez/4c6c95ffea7a84cf4fc76348a578f18d to your computer and use it in GitHub Desktop.
Async and Errors in Typescript
This file contains 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
const promiseAndError = async (n: number): Promise<any> => { | |
if (n == 666) { | |
throw new Error("truly bad news"); | |
} | |
if ( n < 0 ) | |
throw new Error("Negative n illegal"); | |
if ( n % 2 == 1 ) | |
return Promise.resolve({result: "odd"}); | |
else | |
return Promise.resolve({result: "even"}); | |
} | |
// https://2ality.com/2016/03/promise-rejections-vs-exceptions.html | |
// https://thecodebarbarian.com/async-functions-in-javascript.html#error-handling | |
// | |
// https://twitter.com/bterlson/status/713402741733785600?s=20 | |
// "TC39 says no. Originally, param initializer exprs would throw out of async | |
// functions but now rejects promise. For the best, IMO." | |
// | |
// So, do a reject | |
const isEvenOrNegative = async (n: number): Promise<boolean> => { | |
console.log(`>>> Testing ${n}`); | |
try { | |
if (n == 999) { | |
// Sneaky n thing throws from here | |
throw new Error("999 almost got through."); | |
} | |
return promiseAndError(n).then( | |
({result}) => { | |
return new Promise((resolve, reject) => { | |
resolve(result == "even"); | |
})}); | |
} catch(err) { | |
// This is the failure of promiseAndError | |
return Promise.reject(err); | |
} | |
}; | |
const main = async () => { | |
// test could be parameterized... | |
try { | |
console.log(await isEvenOrNegative(666)); | |
} catch (err) { | |
console.log(`try/catch: ${err}`); | |
} | |
try { | |
console.log(await isEvenOrNegative(999)); | |
} catch (err) { | |
console.log(`try/catch: ${err}`); | |
} | |
// This needs await to execute the reject. | |
await isEvenOrNegative(666).then( | |
(x) => console.log(`Shouldnt' be ${x}`) | |
).catch( | |
(err) => console.log(`promise.catch: ${err}`)); | |
await isEvenOrNegative(999).then( | |
(x) => console.log(`Shouldnt' be ${x}`) | |
).catch( | |
(err) => console.log(`promise.catch: ${err}`)); | |
// 0 | |
try { | |
console.log(await isEvenOrNegative(0)); | |
} catch (err) { | |
console.log('no way'); | |
} | |
// < 0 | |
try { | |
console.log(await isEvenOrNegative(-1)); | |
} catch (err) { | |
console.log(`should be neg: ${err}`); | |
} | |
await isEvenOrNegative(-999).then( | |
(x) => console.log(`Shouldnt' be ${x}`) | |
).catch( | |
(err) => console.log(`promise.catch neg: ${err}`)); | |
} | |
main(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment