I have the following function:
const findUserByEmail = (email) => {
var user
MongoClient.connect(url, (err, db) => {
const dbo = db.db('users')
dbo.collection('users').findOne({email: email}, (err, result) => {
if (err) throw err
else return result
})
db.close()
}).then((user) => {
return user
})
}
I am trying to return the value of user so that findUserByEmail(email)=user but can't figure out how. I have tried using async/await and promises to return this value to get around Node's asynchronous nature however in each I could not get the value to return to the main function. In this case, return user returns the user to the then() function, which is not correct.
Any help would be much appreciated.
Your very close but there is one thing your missing with your function findUserByEmail it needs to return a Promise. With a Promise you can call resolve in the future with the result from findOne. This will also change how you consume the findUserByEmail function.
Example
const findUserByEmail = (email) => {
return new Promise((resolve, reject) => {
MongoClient.connect(url, (mongoError, db) => {
if (mongoError) {
return reject(mongoError)
}
const dbo = db.db('users')
dbo.collection('users').findOne({ email: email }, (findError, user) => {
if (findError) {
return reject(findError)
}
db.close();
return resolve(user)
})
})
})
}
To consume this function you can use Promise.then(user => ) or the preferred approach of using async/await.
Consuming using .then()
findUserByEmail("email.com").then(user => {
// do something
}).catch(err => {
// do something
})
Consuming using async/await
async function test() {
try {
const user = await findUserByEmail("email.com");
// do something
} catch (error) {
// do something
}
}
Related
After searching through countless posts I don't understand why I'm still getting a Promise pending after my awaits. The code below should explain it but I'm trying to pull a MongoDB query of the max value of a column/schema. The console.log within the function is giving me the correct timestamp but I'm trying to pass that out of the inner scope and function to another function.
This is pure NodeJS with only MongoDB imported. Can this be done without any external packages?
export async function getMaxDate() {
var time = MongoClient.connect(url, { useUnifiedTopology: true }, function (err, db) {
if (err)
throw err;
var dbo = db.db(getDB);
dbo.collection(getColl)
.find()
.limit(1)
.sort({ 'timestamp': -1 })
.toArray(function (err, result) {
if (err)
throw err;
time = result[0].time; // THIS IS GIVING THE CORRECT VALUE
console.log(time)
db.close();
});
});
return time
}
export async function getMax() {
var block = await getMaxDate();
return block
}
var t = getMax();
console.log(t); // THIS IS GIVE ME A PROMISE PENDING
getMax() returns a promise, you have to wait for it.
var t = await getMax()
Also getMaxDate uses an async callback that you want to promisify:
export async function getMaxDate() {
return new Promise((resolve,reject) => {
MongoClient.connect(url, { useUnifiedTopology: true }, function (err, db) {
if (err)
return reject(err);
var dbo = db.db(getDB);
dbo.collection(getColl)
.find()
.limit(1)
.sort({ 'timestamp': -1 })
.toArray(function (err, result) {
if(err)
reject(err);
else {
let time = result[0].time; // THIS IS GIVING THE CORRECT VALUE
console.log(time)
db.close();
resolve(time);
}
});
})
});
}
For reference, A is the same thing as B here:
async function A(x) {
if(x)
throw new Error('foo');
else
return 'bar';
}
function B(x) {
return new Promise((resolve,reject)=>{
if(x)
reject(new Error('foo'));
else
resolve('bar');
});
}
Promises came first, then async/await notation was introduced to make common Promise coding practices easier
You can use A and B interchangeably:
async function example1() {
try {
await A(1);
await B(0);
}
catch(err) {
console.log('got error from A');
}
}
async function example2() {
return A(0).then(()=>B(1)).catch((err)=>{
console.log('got error from B');
})
}
I'm fairly new to nodejs and have stumbled into a problem with my code.
The documentation for SQL Server and a guide I found on Youtube both handle their code this way, but after starting to use bycrypt I've noticed my function ends after the request is complete although I'm using .then().
Anyways, here's my code so far:
router.post('/login', (req, res) => {
getLoginDetails(req.body.username, req.body.password).then(result => {
console.log(result);
res.json(result);
})
});
async function getLoginDetails(username, password) {
await pool1Connect;
try {
const request = pool1.request();
request.input('username', sql.NVarChar, username);
request.query('SELECT * FROM users WHERE username = #username', (err, result) => {
if (err) {
return ({err: err})
}
if (result.recordset.length > 0) {
bcrypt.compare(password, result.recordset[0].user_password, (err, response) => {
if (response) {
console.log(result.recordset);
return(result.recordset);
} else {
return({message: "Wrong password or username!"})
}
})
return(result)
} else {
return({message: "user not found!"})
}
})
} catch (err) {
return err;
}
}
I tried logging both the request and the return value from the function getLoginDetails and the request log came faster, so I assume it's not waiting for the program to actually finish and I can't figure out why...
Sorry if that's obvious, but I'd love to get some help here!
EDIT:
router.post('/login', async (req, res) => {
// res.send(getLoginDetails(req.body.username, req.body.password))
await pool1Connect
try {
const request = pool1.request();
request.input('username', sql.NVarChar, req.body.username);
request.query('SELECT * FROM users WHERE username = #username', (err, result) => {
console.log(result);
bcrypt.compare(req.body.password, result.recordset[0].user_password, (err, response) => {
if (response) {
res.send(result);
} else {
res.send('wrong password')
}
})
//res.send(result)
})
} catch (err) {
res.send(err);
}
});
This code works, but when I tried to encapsulate it in a function it still didn't work.
#Anatoly mentioned .query not finishing in time which makes sense, but I thought mssql .query is an async function?
Your problem arises from an wrong assumption that callbacks and promises are alike, but on the contrary callbacks don't "respect" promise/async constructs
When the program hits the bottom of getLoginDetails the progrm execution has already split into 2 branches one branch returned you the (empty) result whereas the other one still busy with crypto operations.
Though it is true that an async function always returns a promise but that doesn't cover any future callbacks that might execute inside it. As soon as node reaches the end of function or any return statement the async function's promise get resolved(therefore future callbacks are meaningless), what you can do instead is handroll your own promise which encampasses the callbacks as well
router.post('/login', (req, res) => {
getLoginDetails(req.body.username, req.body.password))
.then((result)=>{
res.send(result);
})
.catch((err)=>{
res.send(err);
})
});
async function getLoginDetails(username, password) {
await pool1Connect
return new Promise( (resolve,reject) => {
try {
const request = pool1.request();
request.input('username', sql.NVarChar, username);
request.query('SELECT * FROM users WHERE username = #username', (err, result) => {
console.log(result);
bcrypt.compare(password, result.recordset[0].user_password, (err, response) => {
if (response) {
resolve(result);
} else {
resolve('wrong password')
}
})
})
} catch (err) {
reject(err);
}
});
}
You didn't return any result to getLoginDetails. Either you use async versions of request.query and bcrypt.compare (if any) or wrap request.query to new Promise((resolve, reject) like this:
const asyncResult = new Promise((resolve, reject) => {
request.query('SELECT ...
...
if (err) {
resolve({err: err}) // replace all return statements with resolve calls
}
...
})
const queryResult = await asyncResult;
I want to use the async function to bring out a particular value from my database to my the function global so I can use it in other parts of my application.
async function dimension() {
const result = await Settings.find({_id : "5d7f77d620cf10054ded50bb"},{dimension:1}, (err, res) => {
if(err) throw new Error(err.message, null);
const holder = res[0].dimension;
return holder;
console.log(holder) /// this print the expected result, that i want to make global
});
return {
result
};
};
console.log(dimension())
but the console.log of the dimension() gives me this
Promise { <pending> }
instead of the same value that
console.log(holder)
gives me nothing.
The problem is you are printing the result of dimension() as soon as you call it, but since this function is async, it returns a promise that is not yet resolved.
You do not need to use async/await here. Settings.find() seems to return a Promise. You can just return directly this Promise and use .then() to do something once that promise is resolved.
Like this :
function dimension () {
return Settings.find({ _id: '5d7f77d620cf10054ded50bb' }, { dimension: 1 }, (err, res) => {
if (err) {
throw new Error(err.message, null);
}
return res[0].dimension;
});
}
dimension().then(result => {
//print the result of dimension()
console.log(result);
//if result is a number and you want to add it to other numbers
var newResult = result + 25 + 45
// the variable "newResult" is now equal to your result + 45 + 25
});
More info on Promises and async/await
You have to await for your result, like this:
const result = await dimension();
console.log(result);
In that case, you don't even to make the original function async, just write it like this:
function dimension() {
return Settings.find({_id : "5d7f77d620cf10054ded50bb"},{dimension:1}, (err, res) => {
if(err) throw new Error(err.message, null);
const holder = res[0].dimension;
return holder;
});
};
async function myGlobalFunc() {
const result = await dimension();
console.log(result);
}
The best way to have this globally available is to just put your function dimension in a file somewhere. Then where you need the value, you just require it and await its value. E.g.
// get-dimension.js
// ...const Settings = require... comes here
module.exports = function getDimension() {
return Settings.find({_id : "5d7f77d620cf10054ded50bb"},{dimension:1}, (err, res) => {
if(err) throw new Error(err.message, null);
const holder = res[0].dimension;
return holder;
});
}
// your other modules, e.g.
// my-service-handler.js
const getDimesion = require('./get-dimension');
async function myServiceHandler() {
const dimension = await getDimension();
// do stuff with dimension.
}
You're using async/await, but you're mixing it with callbacks, this is not desirable as it leads to confusion. It's not clear what you expect to happen in the callback, but return holder; likely doesn't do what you expect it to do, returning from a callback does not work the same way returning from a promise handler works. Your entire implementation should work with promises so that the async/await syntax reads more naturally (as it was intended).
async function dimension() {
// We're already awaiting the result, no need for a callback...
// If an error is thrown from Settings.find it is propagated to the caller,
// no need to catch and rethrow the error...
const res = await Settings.find({_id: "5d7f77d620cf10054ded50bb"}, {dimension: 1});
return {result: res[0].dimension};
}
(async () => {
try {
console.log(await dimension());
} catch (err) {
console.error(err);
}
})();
Use dimension().then() in your code then it will work fine.
async function globalDimension() {
const data = await Users.findOne({ phone: 8109522305 }).exec();
return data.name;
}
globalDimension().then(data => {
console.log(data);
});
I am trying to send the response when the loop k value is equal to users[0].employees.length, but it's directly moving forward to max length, how do I solve it
Userlist.find(queryObj).exec(function (err, users) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
}
else {
console.log('found users list', users);
// res.json(users[0].employees);
var k=0;
var resparr=[]
for(var i=0;i<users[0].employees.length;i++){
k++;
User.find({"_id":users[0].employees[i]._id}).exec(function(err,user){
resparr=resparr.concat(user);
console.log("resparray:",k,resparr.length,i,users[0].employees.length)
if(k==users[0].employees.length)
{
console.log("success",resparr)
res.json(resparr);
}
})
}
}
});
You are using an asynchronous function call within a synchronous loop. The loop will always finish before your callback functions are called.
You will need some kind of asynchronous looping. For a native solution you can use Promises:
const getUser = (id) => {
return new Promise((resolve, reject) => {
User.find({ '_id': id })
.exec((err, user) => {
if (err) reject(err);
else resolve(user);
});
});
};
const promises = users[0].employees.map(({ _id: id }) => getUser(id));
Promise.all(promises)
.then(users => res.json(users))
.catch(err);
For utility packages in node.js, I'd recommend the package async for a callback based solution or bluebird for Promises. Both have a .map function which is perfect for this use case.
token in the below snippet is always undefined. Can someone help me out figuring what's wrong here?
[err, token] = await to(comparePassHash(body.password, user.password));`
comparePassHash = async (pass, hash) => {
bcrypt.compare(pass, hash, (err, token) => {
if (err) TE(err);
console.log('test');
return token;
});
};
to = (promise) => {
return promise
.then(data => {
return [null, data];
}).catch(err =>
[pe(err)]
);
};
It's undefined because that's what comparePassHash resolves.
async keyword won't work as you expect in that case. You're returning token inside .compare function, not inside comparePassHash. You have to wrap bcrypt.compare with a Promise.
const comparePassHash = (pass, hash) => {
return new Promise((resolve, reject) => {
bcrypt.compare(pass, hash, (err, token) => {
if (err)
return reject(err);
console.log('test');
return resolve(token);
});
});
};
Take your function:
comparePassHash = async (pass, hash) => {
bcrypt.compare(pass, hash, (err, token) => {
if (err) TE(err);
console.log('test');
return token;
});
// implicit return: undefined
};
Without an await it will execute bcrypt.compare, it will not wait until it finishes, since it's not a promise, and it will exit the function, returning undefined since you're missing a return statement.
Another way is to use Util.promisify
const { promisify } = require('util');
const comparePassHash= promisify(bcrypt.compare);
// This must be inside an async function
[err, token] = await to(comparePassHash(body.password, user.password));