3 patterns for writing async code in Javascript
1 min readJul 18, 2021
Three useful patterns to make better use of async/await code in Javascript
1. Use .catch
function instead of handleError
Don’t: Pass handleError
directly as a second parameter of .then
. handleError
does not catch error thrown by process
:
getPromise().then(process, handleError)
Do: Pass handleError
in .catch
. .catch
works for errors thrown by either getPromise
or process
:
getPromise().then(process).catch(handleError)
2. Use finally to execute some code after a promise fulfils or rejects
Don’t: Invoke the same code in .then
and .catch
myPromise
.then(response => {
doSomething(response)
runFinalCode()
})
.catch(e => {
returnError(e)
runFinalCode()
})
Do: Make use of finally
myPromise
.then(response => {
doSomething(response)
})
.catch(e => {
returnError(e)
})
.finally(() => {
runFinalCode()
})
3. Wrapping ephemeral resources inside an async function
This pattern builds on the previous one to make sure the resources are released when the function resolves or crashes.
const withTempDir = async (fn) => {
const dir = await fs.mkdtemp(
await fs.realpath(os.tmpdir()) + path.sep
)
try {
return await fn(dir)
} finally {
fs.rmdir(dir, {recursive: true})
}
}
await withTempDir((dir) => {
// use dir to store temporary things
// dir will always be delete when this function finishes or crashes
})