I have this simple code where an async function is called. The promise is chained with .then().catch(). When the promise gets rejected, it prints Came to catch block
and Async operation succeeded
as expected.
async function exampleAsyncFunction() {
try {
const someAsyncOperationP = someAsyncOperation().then(
() => console.log(`Came to then block`))
.catch(() => console.log(`Came to catch block`));
const result = await someAsyncOperationP;
console.log('Async operation succeeded:', result);
} catch (error) {
console.error('Async operation failed:', error);
}
}
async function someAsyncOperation(): Promise < number > {
return new Promise < number > ((resolve, reject) => {
reject(new Error('Random error occurred'));
});
}
// Call the async function
exampleAsyncFunction();
However, if I slightly change this code to the following where I assign the promise to a const and then attach the .then().catch() to it, then I see it goes to the Async operation failed: Error: Random error occurred
block and then see the Came to catch block
line.
async function exampleAsyncFunction() {
try {
const someAsyncOperationP = someAsyncOperation();
someAsyncOperationP.then(
() => console.log(`Came to then block`))
.catch(() => console.log(`Came to catch block`));
const result = await someAsyncOperationP;
console.log('Async operation succeeded:', result);
} catch (error) {
console.error('Async operation failed:', error);
}
}
async function someAsyncOperation(): Promise < number > {
return new Promise < number > ((resolve, reject) => {
reject(new Error('Random error occurred'));
});
}
// Call the async function
exampleAsyncFunction();
I expected both these blocks of code to have the same behavior. Why do we see this difference?