I’m converting some code from .then/.catch
to async/await
. I need to access the original promise that fails in the catch block for logging purposes.
Orignal code:
const myPromise = somePromise()
myPromsise.then(() => {
//...
}).catch((error) => {
errorLogger(error, myPromise) // The way we log things requires the original promise to be passed to the error logger.
}
With try catch
try {
const myPromise = await somePromise()
//...
} catch (error) {
errorLogger(error, myPromise) // myPromise is not available in catch block due to scope.
}
How can I access the promise in the catch block?
2
Answers
You’re not setting
myPromise()
to the promise. By usingawait
you’re setting it to what the promise resolves to.To get the promise itself, assign the function to a variable without using
await
. You can then useawait
separately to get the resolved value.Why? This doesn’t make sense, there are many ways code can fail without a promise being available. Really all the information that the logger needs should be contained in the error object that is thrown as the exception. Fix your logging.
But if you must, I would start with