Tuesday 29 May 2018

How to wait for array.map(/*make a db request*/) to finish before moving on?

I'm using the 'mssql' module, and I need to run multiple prepared statements based on some data I gathered earlier in my app.I'm trying to do something like this:Promise.all(tables.map(table => { doSQLStatements(table) }); closeDbConnections() function doSQLStatements(table) { return new Promise((resolve,reject) => { table.Keys.map(key => { let req = sql.PreparedStatement(/*stuff*/) req.prepare(/*stuff*/) .then(() => { req.execute(/*stuff*/) }) .then(results => { /**do stuff to results**/ console.log(results); }) .catch(err => {console.log(err)}); }) console.log("**get here only after all results processed**"); }) } And I'd like to wait for the /**do stuff to results**/ of each iteration of arr.map() to finish. Unfortunately, console.log("get here only after all results processed") for each table is being called before console.log(results) for any keys.The console ends up like:**get here only after all results processed** **get here only after all results processed** **get here only after all results processed** results for table1 key1 results for table1 key2 results for table3 key1 results for table3 key2 results for table2 key1 results for table2 key2 When it should be:results for table1 key1 results for table1 key2 **get here only after all results processed** results for table3 key1 results for table3 key2 **get here only after all results processed** results for table2 key1 results for table2 key2 **get here only after all results processed** Is there some way to force it to go through arr.map() synchronously then finish the function?

Submitted May 29, 2018 at 04:21PM by I_HAVE_THAT_FETISH

No comments:

Post a Comment