I'm passing an async function to an array reduce function. What's the syntax for catching errors thrown by the passed in function? The reducing is happening inside a try catch block, which is catching other errors just fine, but node gives me an UnhandledPromiseRejectionWarning if the passed in function itself throws an error.
Code:
aFunction = async (anArray) => {
try {
const result = await anArray.reduce(async (a, b) => {
await doSomethingTo(b);
}, Promise.resolve());
return result;
}
catch (error) {
winston.error(error);
}
}
(Edit) Actual code:
exports.chainedQueryDB = async (queries, finalTask, download) => {
let client = await pool.connect();
try {
winston.info(`Begin chained table query.`);
// Loop through query array
const result = await queries.reduce(async (a, b) => {
await client.query(b);
}, Promise.resolve());
if (download) {
return streamOut(download, client);
}
return result.rows;
}
catch (error) {
throw error;
}
finally {
const final = await client.query(finalTask);
winston.info(`Temp table dropped.`);
client.release();
}
}
(Edit) Report:
Replacing await client.query(b) with await a; return client.query(b); solved the problem. With just await client.query(b), reduce seemed to 1) generate a bunch of floating client.query calls that all ran even if an earlier promise was rejected, and 2) caused an unhandled promise rejection warning. Using await a; return client.query(b); stops execution on first rejection and the catch block catches the error as originally intended.
resultto be? Why are you usingreduce? Do you want thedoSomethingtasks to happen concurrently?anArrayis a set of Postgres queries that need to happen in sequence.resultis the result of the final pg query operation, and is returned to the calling function. The code works as written, but simulating a database error causes node to throwUnhandledPromiseRejectionWarning.resultis alwaysundefined.anArrayin sequence andresultdefinitely holds the value I expect. What am I missing?doSomething- maybe it does some internal queuing?