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

88
Vistas
Express not awaiting MongoJS Function

I've set up a function for my Express JS endpoint to 'await' to get a result from a Mongo DB using Mongo JS.

Function:-

async function getIntroducer(company){


  const intro = await dbIntro.collection('introducers').findOne({company: company},  function(err, doc) {
 
 console.log("🚀 ~ file: app.js ~ line 289 ~ intro ~ doc.introducer", doc.introducer)
   return doc.introducer
  });
  
  
  return intro

  //return intro;
};

Express JS Endpoint:-

app.post(
  "/case",
  passport.authenticate("accessToken", { session: false }),
  async function (req, res) {
    const body = req?.body;
    
    const intro = await getIntroducer(req.user.company);
    console.log("🚀 ~ file: app.js ~ line 1152 ~ intro", intro)

Current behaviour, :-


🚀 ~ file: app.js ~ line 1152 ~ intro undefined

Then the result sends, then thereafter I get this in console (aka it's not awaiting):-


🚀 ~ file: app.js ~ line 289 ~ intro ~ doc.introducer 347501

I've also tried completely getting rid of 'const intro' and just straight returning it. And I've also tried getting rid of the callback function but MongoJS says 'CB is not a function'

Any help please?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You're mincing different styles of asynchronous implementations (callback and promise) when querying the collection.

Seeing as the mongojs library supports only the callback style. You need to promisify the findOne operation to await it.

There is the promisify library in the util module that can aid in this goal inasmuch as the callback signature is a function that is called with an error and/or a result.

For example, to promisify the findOne so that it can be awaited, you can write

const util = require('util');

async function getIntroducer(company){
  const findOneDbIntro = util.promisify(dbIntro.collection('introducers').findOne);
  let intro;
  try {
    intro = await findOneDbIntro({company: company});
  }
  catch (err) 
  {
    // log error with your logging library.
  }
//...
}

This gives a similar result to doing by hand. The Promise object is well documented on MDN:

async function getIntroducer(company){
  let intro;
  try {
    intro = await new Promise(
      (resolve, reject) => {
        dbIntro.collection('introducers').findOne({company: company},
          function (err, doc) {
          if(err) {
            reject(err);
          }
          resolve(doc);
       });
    });
  } catch (err) 
  {
    // log error with your logging library.
  }
    //...
}
about 4 years ago · Juan Pablo Isaza 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