Search code examples
javascriptnode.jses6-promise

how to wait till DB connection is made and queries are executed for each database in an array


A file contains json data with details of database. For each database connection, a series of queries need to be executed. Currently, the map function is waiting for the database connection.

Below is the start function

function start() {
 console.log('function initiated');
  try {
    let jsonData = fs.readFileSync('../request.json');
    let jsonString = JSON.parse(jsonData);

    //jsonString['request'].forEach(async function(json) {
    jsonString['request'].map(async json => {
      dbdetails = json.dbdetails;
      //dbdetails.forEach(async function(db){
      await dbbdetails.map(async db => {
        console.log('pdbdetails: ' + db);
        connString = json.connString;

        //makes the DB connection
        await connectDB(db.userId, db.Password, connString)
          .then(async conn => {
            await execution(conn, pdbDetails, vmUser, vmPassword, ip);
          })
          .catch(err => {
            console.log(err);
          });
        console.log('after each execution');
        //}
      });
    });
  } catch (err) {
    console.log(err.message);
    return;
  }
}

Below function is to make a database connection and return the connection

function connectDB(oUser, oPassword, connString) {
  console.log('inside connectDB');
  return new Promise((resolve, reject) => {
    oracledb.getConnection(
      {
        user: oUser,
        password: oPassword,
        connectString: connString
      },
      function(err, connection) {
        if (err) {
          console.error(err.message);
          reject(err);
          //throw err;
        }
        console.log('returning connection');
        //console.log(connection);
        resolve(connection);
        //return connection;
      }
    );
  });
}

below is the function which executes servies of queries on database

  function execution() {
     /// series of sql query execution
    }

Solution

  • Not sure what you’re trying to do exactly, but sounds like the problem is that .map doesn’t wait for your async functions. If you have to do them one at a time, use a for loop:

    for ( var item of array ) {
        await item.something();
    }
    

    To do them all at once:

    var results = await Promise.all( array.map( item => item.something() )