Skip to content

Instantly share code, notes, and snippets.

@zaydek
Created March 10, 2021 20:06
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 zaydek/c8f0da3fd2badcf02feccc73ea3e232e to your computer and use it in GitHub Desktop.
Save zaydek/c8f0da3fd2badcf02feccc73ea3e232e to your computer and use it in GitHub Desktop.
async function on<T>(fn: () => T | Promise<T>): Promise<[T | null, Error | null]> {
try {
const res = await fn()
return [res, null]
} catch (error) {
return [null, error]
}
}
function sleep(ms: number): Promise<void> {
return new Promise(resolve => {
setTimeout(() => {
resolve()
}, ms)
})
}
async function fn(): Promise<string> {
await sleep(1_000)
return "Hello, world!"
}
async function main(): Promise<void> {
const [res, err] = await on(() => fn())
if (err !== null) {
console.log("here", err)
return
}
console.log(res)
}
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment