I have nodejs module to fetch data from mongodb database using mongodb driver. Callback is passed to given function which return a promise, but instead of returning result in.then() function, it is passing value to callback function. How can I call this function from other module or function since it is not returning it in.then()? I tried to console the result of.then(), but it is showing undefined.
const MongoClient = require('mongodb').MongoClient; const Db = require('../model/db'); Db.findUser = (details, callback) => { return dbconnection().then(db => { if (db) { return db.collection('users').findOne({ email: details.email, pass: details.password }).then(data => { if (data) { console.log('Found one'); callback(true); } else { let err = new Error(); callback(err); } }) }
I have used following function to call the promise. I am new to promises.
var getUser = function(callback) { db.findUser().then(result => { console.log(result) // undefined }) }
You can easily do it using async/await
. Something like this:
Db.findUser = async (details, callback) => {
const db = await dbconnection();
const data = await db.collection('users').findOne({
email: details.email,
pass: details.password
});
if (data) {
console.log('Found one');
callback(true);
} else {
let err = new Error();
callback(err);
}
return data;
}
and consume it like:
const getUser = async (details, callback) => {
const data = await Db.findUser();
// do whatever you need with data
return data;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.