I have an issue with promises.
mongoDb.getFromDb(req.body.firstName, req.body.lastName)
.then(
rows => {
console.log(rows.count()); // Promise { <pending> }
}
}
The log is: Promise { <pending> }
.
I read about this state:
Pending - until a Promise is fulfilled it is in pending state
That's why, I use .then()
method.
As I read, .then()
method takes a function that will be passed the resolved value of the Promise once it is fulfilled.
So if it was fulfilled, why is the state pending?
If it's relevant, this is getFromDb
function:
// Use connect method to connect to the Server
function init() {
connectingDb = new Promise(
function (resolve, reject) {
MongoClient.connect(url, function (err, db) {
if (err) {
console.log('Unable to connect to the mongoDB server. Error:', err);
reject(err);
}
else {
console.log('Connection established to', url);
resolve(db);
}
});
}
);
}
UPDATE #1 (torazaburo
's comment):
function getFromDb(firstName, lastName) {
return connectingDb
.then(myDb => {
return myDb.collection('alon').find({
"firstName": firstName,
"lastName": lastName
})
})
.catch(err=> { return err; })
}
(I'm still getting Promise { <pending> }
)
Update #2 (noisypixy
's comment):
var mongodb = require('mongodb'); var MongoClient = mongodb.MongoClient;
Thanks.