Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading