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

126
Visualizações
Data not returning from async function with database connection

The goal is to call a function from my main script that connects to a database, reads a document from it, stores pieces of that document in a new object, and returns that object to my main script. The problem is I cannot get it all to work together. If I try one thing, I get the results but my program locks up. If I try something else I get undefined results.

Long story short, how do I open a database and retrieve something from it to another script. The program is a quiz site and I want to return the quiz name and the questions.

const myDb = require('./app.js');

var myData = myDb.fun((myData) => {
    console.log(myData.quizName);
});

Here is the script that tries to open the database and find the data

const { MongoClient } = require("mongodb");
const {mongoClient} = require("mongodb");

const uri = connection uri goes here but my name is hard coded into it at the moment so I removed for privacy

const client = new MongoClient(uri);

const fun = async (cback) => {
  try {
    await client.connect();

    const database = client.db('Quiz-Capstone');
    const quizzes = database.collection('Quiz');

    const query = {quizName: "CIS01"};

    const options = {
      sort: {},
      projection: {}
    };

    const quiz = await quizzes.findOne(query, options);

    var quizObject = {
      quizName: quiz.quizName,
      quizQuestions: quiz.quizQuestions
    }

    //console.log(testOb);

  } finally {
    await client.close();
    cback(quizObject);
  }
}


fun().catch(console.dir);


module.exports = {
  fun: fun
}

UPDATE: Still stuck. I have read several different threads here about asynchronous calls and callbacks but I cannot get my function located in one file to return a value to the caller located in another file.

about 4 years ago · Juan Pablo Isaza
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