Answer the question
In order to leave comments, you need to log in
How to pull the value of a variable from a nested await call to an async function in ES7?
I'm trying to get a boolean value from async
a function that has a nested anonymous async
function in it. Perhaps it will be clearer in the code:
async userExistsInDB(email) {
let userExists;
await MongoClient.connect('mongodb://127.0.0.1:27017/notificator', async(err, db) => {
if (err) throw err;
let collection = db.collection('users');
userExists = await collection.find({email: email}).limit(1).count() > 0;
console.log("INSIDE:\n", userExists);
db.close();
});
console.log("OUTSIDE:\n", userExists);
return userExists;
}
async getValidationErrors(formData) {
let userExists = await this.userExistsInDB(formData.email);
console.log("ANOTHER FUNC:\n", userExists);
}
OUTSIDE:
undefined
ANOTHER FUNC:
undefined
INSIDE:
true
Answer the question
In order to leave comments, you need to log in
I'm not 100% sure but... from what you wrote:
you need to remove the callback. Regarding error handling from the async-functions specification, we should rewrite the function like this:
async userExistsInDB(email) {
let userExists;
try {
const db = await MongoClient.connect('mongodb://127.0.0.1:27017/notificator');
} catch (err) {
throw err; // тут у вас никакой обработки ошибок небыло... можно и без try/catch тогда
}
const collection = db.collection('users');
userExists = await collection.find({email: email}).limit(1).count() > 0;
console.log("INSIDE:\n", userExists);
db.close();
console.log("OUTSIDE:\n", userExists);
return userExists;
}
It turned out like this in the end:
async userExistsInDB(email) {
let db = await MongoClient.connect('mongodb://127.0.0.1:27017/notificator');
try {
let collection = db.collection('users');
let userCount = (await collection.find({email: email}).limit(1).count());
return userCount > 0;
} finally {
db.close();
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question