Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

138
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda