JavaScript error handling async function passed to reduce -


i'm passing async function array reduce function. what's syntax catching errors thrown passed in function? reducing happening inside try catch block, catching other errors fine, node gives me unhandledpromiserejectionwarning if passed in function throws 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;   }    {     const final = await client.query(finaltask);     winston.info(`temp table dropped.`);     client.release();   } } 

(edit) report: replacing await client.query(b) await a; return client.query(b); solved problem. await client.query(b), reduce seemed 1) generate bunch of floating client.query calls ran if earlier promise rejected, , 2) caused unhandled promise rejection warning. using await a; return client.query(b); stops execution on first rejection , catch block catches error intended.

you need promise in accumulator (the a parameter) - await it, handle errors installing .catch() callback, wait concurrently dosomething(b). sequential execution, do

async function afunction(anarray) {   try {     return await anarray.reduce(async (a, b) => {       await a; // make sure previous query done       return dosomethingto(b);     }, promise.resolve());   } catch (error) {     winston.error(error);   } } 

i hover recommend not use reduce here:

async function afunction(anarray) {   try {     let result;     (const b of anarray) {       result = await dosomethingto(b);     }     return result;   } catch (error) {     winston.error(error);   } } 

Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -