Probably worded poorly, I understand async/promises/callbacks.
What I'm trying to do is create a module which can be required (database.js), which I can then call methods such as database.insert() and database.read().
So here is my code:
require('dotenv').config()
const {MongoClient} = require('mongodb');
const client = new MongoClient(process.env.MONGO_URI);
var db, queue;
client.connect().then(e => {
console.log('connected to database');
db = client.db('filemanager');
queue = db.collection('queue');
});
function insert (data, cb) {
queue.insertOne(data)
.then(res => {cb()})
}
module.exports = {
insert: insert,
}
The question is: How do I make it so when database.insert() is called, it will process instantly if db and queue are already defined, but if they aren't it will wait until they are, then will continue processing like normal?
You can assign the result of a promise to a variable, and you can call then on it later. For example:
const queuePromise = client.connect().then(e => {
console.log('connected to database');
const db = client.db('filemanager');
const queue = db.collection('queue');
return queue;
});
Now you have a variable called queuePromise that is a Promise that resolves to a db.collection object. Then you can use that promise like this
queuePromise.then((queue) => {
// do something with the queue
});
So you can have a function like this
const insert = (data, callback) => {
queuePromise.then((queue) => {
queue.insertOne(data).then(callback);
});
};
Or even better, don't use the callback pattern and go like this
const insert = (data) => {
return queuePromise.then((queue) => {
return queue.insertOne(data);
});
};
// use the callback in a `then` after calling `insert`
insert(data).then(callback);