Skip to content

Instantly share code, notes, and snippets.

@chmac
Last active May 28, 2020 12:47
Show Gist options
  • Save chmac/f2635a82fc8e4631b01eb2daf802b06f to your computer and use it in GitHub Desktop.
Save chmac/f2635a82fc8e4631b01eb2daf802b06f to your computer and use it in GitHub Desktop.
JavaScript async error control flow
const work = async () => "success";
work().then(
(result) => {
console.log(result);
},
(error) => {
console.error(error);
}
);
const work = async () => "success";
const start = async () => {
let result
try {
result = await work()
} catch (error) {
console.error(error)
}
console.log(result)
};
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