Reputation: 65
this is my async function
async duplicate_email(db, email) {
await db.collection("users").findOne({ 'email': email }, function(findErr, result) {
console.log(findErr)
if (!result) {
return false
} else {
return true
}
});
}
I call it like this from another file :
middleware.duplicate_email(db, "[email protected]").then((answer) => {
console.log(answer)
});
answer always returns undefined, while result is populated.
Upvotes: 1
Views: 517
Reputation: 3299
You should utilize the async/await promise syntax by setting the mongo call equal to a variable. Something like this:
async duplicate_email(db, email) {
let myResults;
try {
myResults = await db.collection("users").findOne({ 'email': email });
} catch (err) {
console.log(err);
}
return myResults ? true : false;
}
You can then consume the promise returned by duplicate_email
middleware.duplicate_email(db, "[email protected]").then((answer) => {
console.log(answer)
});
That's the beauty of using async / await. You no longer need the callbacks. However, for error trapping, you'll need the try
catch
block.
Upvotes: 0
Reputation: 14904
Here is an short solution
Just return the result and invert it twice. You will get either true
or false
async duplicate_email(db, email) {
try {
return !!(await db.collection("users").findOne({ 'email': email }))
}catch(err) {
console.log(err)
}
}
Upvotes: 0
Reputation: 4040
async duplicate_email(db, email) {
let availableEmail = await db.collection("users").findOne({ 'email': email })
if (!availableEmail) {
return false
} else {
return true
}
});
}
if you are using async function then dont use callback.
Upvotes: 0