I'm trying to prepare a general function which will allow me to use any function on any database/collection. I'm not sure im doing this correctly. Here's my function code in node.js:
function use_db(db_url, func, ...args) {
let prom;
// noinspection JSIgnoredPromiseFromCall
var lele = MongoClient.connect(db_url, (error, client) => {
console.log('Connected');
const db = client.db();
console.log(db);
prom = func(db, ...args);
client.close();
console.log('Disconnected successfully');
});
console.log(lele, 'whaat?');
return prom;
}
I want it to return value prom
but this happens:
first output is
console.log(lele, 'whaat?');
which value isundefined 'whaat?'
then
'Connected'
and the last is
'Disconnected successfully'
So obviously prom
is not defined at this moment
Why output is in this order? Why console.log(lele, 'whaat?');
runs first?
Any ideas how can I improve this function, so it will use any other function to work on specific mognoDB database?
EDIT://
function connectDB(db_url) {
return new Promise((res, rej) => {
MongoClient.connect(db_url, (error, client) => {
if (error) return rej(error);
console.log('Connected');
const db = client.db();
return res({
db,
client
});
});
});
}
async function use_db(db_url) {
console.log('Start');
const {
db,
client
} = await connectDB(db_url);
console.log('After db connection');
return [db, client];
}
let temp_list = use_db(db_url);
const db = temp_list[0];
const client = temp_list[1];
let no_user = can_create_user(db, temp_email);
if(no_user) {
//some code
}
How Can I leave active connection to the database and use db
everytime for other functions? It doesn't wait for promise to resolve