Search code examples
javascriptpromisenode-oracledb

How to write Promise chain?


When I'm trying to make some database searching,I'd found two kind of codes to do this.But I don't know which is prefer and why..

// a.js
export default oracledb.createPool(configuration)

the first way(it seems work well,but not meet the promise specifications):

// b.js
import main from a.js;
main.then((pool)=>{
    pool.getConnection().then((connection)=>{
        connection.execute(sql).then((result)=>{
           console.log(result);
           connection.close();
        }).catch(err=>{
           if(connection){connection.close()}
        })
    });
})

here is the second way:

let connection;
main.then((pool)=>{
    return pool.getConnection()
}).then((connection)=>{
   return connection.execute(sql)
}).then((result)=>{
   console.log(result);
   connection.close();
}).catch(err=>{
   if (connection){connection.close()}
});

This problem may not just about database operation, but the right way to organize promise chain.Can anyone please help me?


Solution

  • Use This Documentation https://oracle.github.io/node-oracledb/doc/api.html

    const mypw = ...  // set mypw to the hr schema password
    
    async function run() {
    
      let connection;
    
      try {
        connection = await oracledb.getConnection(  {
          user          : "hr",
          password      : mypw,
          connectString : "localhost/XEPDB1"
        });
    
        const result = await connection.execute(
          `SELECT manager_id, department_id, department_name
           FROM departments
           WHERE manager_id = :id`,
          [103],  // bind value for :id
        );
        console.log(result.rows);
    
      } catch (err) {
        console.error(err);
      } finally {
        if (connection) {
          try {
            await connection.close();
          } catch (err) {
            console.error(err);
          }
        }
      }
    }
    
    run();