Last active
May 28, 2020 12:47
-
-
Save chmac/f2635a82fc8e4631b01eb2daf802b06f to your computer and use it in GitHub Desktop.
JavaScript async error control flow
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 work = async () => "success"; | |
work().then( | |
(result) => { | |
console.log(result); | |
}, | |
(error) => { | |
console.error(error); | |
} | |
); |
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 work = async () => "success"; | |
const start = async () => { | |
let result | |
try { | |
result = await work() | |
} catch (error) { | |
console.error(error) | |
} | |
console.log(result) | |
}; |
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 to = <T>(promise: Promise<T>) => | |
promise.then( | |
(result: T): { result: T; error: undefined } => ({ | |
result, | |
error: undefined, | |
}), | |
(error: Error): { result: undefined; error: Error } => ({ | |
error, | |
result: undefined, | |
}) | |
); | |
const work = async () => "success"; | |
const start = async () => { | |
// NOTE: We cannot destructure here | |
const response = await to(work2('aaa')); | |
if (response.error) { | |
const { error } = response; | |
console.error(error); | |
} else { | |
const { result } = response; | |
console.log(result); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment