简体   繁体   中英

How to properly close a database connection when we return a Promise in NodeJS

I have two function like this:

async getMatches() {
  try {
    const result = await readRowsFromDb('SELECT * FROM matches');
    console.log(result);
  } catch (error) {
    console.error(error);
  }
}

async readRowsFromDb(query) {
  const db = await sqlite.open(this.DATABASE_PATH);
  const promise = db.all(query);
  return promise;
}

getMatches();

The problem is I can't find a right place to put the line

db.close()

AFAIK, I should close the database after I get the result, but the result is in a different function, closing the db inside getMatches doesn't seem right.

I tried closing the database before returning the promise in readRowsFromDb like this

const promise = db.all(query);
db.close();
return promise;

It worked. But I still feel something wrong about it since I close the database connection right after the query is call instead of wait for it to finish, it shouldn't have worked.

Please advice.

If you want readRowsFromDb() to manage the opening and closing of the db (which it kind of has to because nobody else has the db object that you just opened), you can do that this way:

async readRowsFromDb(query) {
  let db;
  try {
      db = await sqlite.open(this.DATABASE_PATH);
      let result = await db.all(query);
      return result;
  } finally {
      if (db) db.close();
  }
}

Keep in mind that because this is an async function, it is still returning a promise that resolves to the result even though you aren't directly returning a promise yourself. That's how async functions work.


The only other way that you could close the db in another function is if you either passed in the db from some other function (so it could manage closing it) or if you returned the db from this function so someone else could use it before closing it. As your readRowsFromDb() function stands now, you have to close it in the function.

make db as a global variable and access it from getMatches ;

let db;
async getMatches() {
  try {
    const result = await readRowsFromDb('SELECT * FROM matches');
    console.log(result);
    return result
  } catch (error) {
    console.error(error);
    return error
  }
}

async readRowsFromDb(query) {
  db = await sqlite.open(this.DATABASE_PATH);
  const promise = db.all(query);
  return promise;
}

getMatches().then((resp) => {
    db.close();
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM