I have a function that returns a Promise. When I am done using that Promise in the .then()
or .catch()
blocks, I always want to execute the same cleanup code. My current setup is this:
const promiseWithFinally = () => {
return new Promise((resolve, reject) => {
// resolve or reject at some point
}).finally(() => console.log('finally done'))
}
promiseWithFinally()
.then(() => console.log('then done'))
.catch(() => console.log('catch done'))
What I want to happen is that either then done
or catch done
get logged first and then finally done
. However it seems to get executed in the exact opposite order - when I resolve the Promise after a timeout of 5 seconds finally done
gets logged first after 5 seconds and then then done
immediately afterwards.
What am I doing wrong or is it possible to do this in general? I know I could just append the .finally()
to each individual function call, but since it's always the same I'd like to put it in the function definition.