This is some code that fetches a result from a database. It connects, makes a query, processes the query, then has to close the DB (under all possible code paths) and return the result.
It seems like the code for closing the database under all circumstances is a bit messy. I'm wondering if there's a cleaner way to do this?
function getBlocked(data) {
let openDb;
close() {
if (openDb) {
openDb.close().catch(err => {
console.log("Error closing db: ", err);
})
}
}
return MongoClient.connect(url).then(db => {
openDb = db;
const blQ = {blocked_user:data.tag_search_mail};
return db.collection("block_list").find(blQ,{"_id":0}).toArray();
}).then(results => {
let blocked = results.map(item => item.blocker);
close();
return blocked; // make this the resolved value of the promise
}).catch(err => {
close();
throw err; // rethrow to keep the promise rejected
})
}
Usage:
getBlocked(data).then(blocked => {
// use blocked array here
}).catch(err => {
// handle error here
});
FYI, it is intentional to return the result without waiting for the DB to close (thus why it's not inserted in the promise chain) and to only log the error, not fail the main operation if closing the db fails.