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

125
Vistas
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 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