Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

254
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!