I'm quite new to async, await and promises. I have an example code here:
export function pollSqsQueue(): Promise<void> {
return receiveMessageFromQueue()
.then((res) => res.Messages || [])
.then(filterMessages)
.then(mapMessagesToObjects)
.then(saveObjects)
.then(deleteMessagesFromQueue)
.catch((error) => {
appLogger.error('Unexpected error when handling queue', error);
});
}
Basically the problem / question is, that if error is thrown in async saveObjects function, why is the deleteMessagesFromQueue still executed? In my understanding it should jump directly to catch block and just log the error.
Edit: the error is actually thrown in here and saveObjects use this function through another async function. Error is not catched anywhere except in the chain above:
export const upsert: (
conn: PoolConnection,
table: string,
fields: string[],
params: any[],
) => Promise<OkPacket> = async (conn, table, fields, params) => {
const sql = `
INSERT INTO
${table} (${fields.join(',')})
VALUES (${', ?'.repeat(fields.length).slice(2)})
ON DUPLICATE KEY UPDATE ${fields.map((field) => `${field}=VALUES(${field})`).join(', ')}
`;
const [result] = await conn.execute<OkPacket>(sql, params);
return result;
};
So if some fields are missing, the upsert will fail and error is thrown. Only thing I get into logs is:
"message":"unhandled promise rejection, promise:{}
.then()
handlers you're asking about. IfsaveObjects
rejects or throws correctly, then it absolutely will skipdeleteMessagesFromQueue
and go right to the .catch()
handler. So, if it's not doing so, then we need to see the code forsaveObjects
because it is apparently not behaving the way you think it is. For example, if you have a plain asynchronous callback insaveObjects
and you're throwing in there, that won't be caught by anything. – jfriend00