Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

137
Views
How do I make a function wait until a database connection is established before continuing?

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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);
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!