Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

259
Vistas
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?

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

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);
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda