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

251
Vistas
How to return an 'await' variable in JavaScript?

I have the following JS code

async function readAtlasAll() {
  return await MongoClient.connect(url, async function(err, db) {
    var dbo = db.db("Users");
    c = dbo.collection("List");
    r = await c.find({}).toArray();
    console.log(r);
    return r;
  });
}

console.log(readAtlasAll());

I'm not sure why, but printing the result of readAtlasAll() comes before printing the variable r inside the function, even though I'm awaiting the result of r beforehand. The terminal prints Promise { <pending> } first and afterwards prints the contents of r. I'm relatively new to JavaScript, so I would really appreciate the help. Thanks!

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

0

You cannot use both await and a plain callback on MongoDB API calls as the await won't do anything useful. Use one or the other, not both. This is because the MongoDB asynchronous APIs will return a promise if you do NOT pass a callback to them and you can then await that promise, but if you pass a callback, they do not return a promise, therefore the await does nothing useful at all. Here's how you would implement it by leaving out the callback and using await:

async function readAtlasAll() {
    const db = await MongoClient.connect(url);
    const dbo = db.db("Users");
    const c = dbo.collection("List");
    const r = await c.find({}).toArray();
    return r;          // this will be the resolved value of the returned promise
}

readAtlasAll().then(r => {
   console.log(r);
}).catch(err => {
    console.log(err);
});

Keep in mind that await has no magic powers at all. ALL it does is suspend execution of the function until a promise resolves/rejects. So, it only does anything useful when you await a promise.

And, further, ALL async functions return a promise so there is NO way to return an asynchronously-retrieved value directly from your function. You have to use an asynchronous mechanism for communicating back an asynchronously retrieved value such as a promise, a callback or an event. So readAtlasAll() can never return your value directly.

See How to return the response from an asynchronous call for more info on that.

about 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