Skip to content

Instantly share code, notes, and snippets.

@AlexBHarley
Created May 31, 2018 09:29
Show Gist options
  • Save AlexBHarley/236fa23b9b39f96446f1d60beece01fc to your computer and use it in GitHub Desktop.
Save AlexBHarley/236fa23b9b39f96446f1d60beece01fc to your computer and use it in GitHub Desktop.
The main issue is that your line
q.query({uid:"dan"})
is not synchronous. So your promise resolves with undefined. You need to do two things:
1. Pass a callback to your query function so you can retrieve the value of your query
2. Resolve the promise with the result of this query.
So here we're passing a callback to your custom `query` function...
module.exports = {
query: function (qry, callback /* this is how you get the result */) {
MongoClient.connect(url, function (err, db) {
if (err) throw err;
var dbo = db.db("invDB");
dbo.collection("products").find(qry).toArray(function (err, result) {
if (err) {
return callback(err);
}
callback(null, result[0]); // here we call the callback
db.close();
});
});
},
...
};
And now we're using the result of that callback to resolve the promise with...
router.get('/getProduct', function (req, res) {
var test = new Promise(function (resolve, reject) {
q.query({ uid: 'dan' }, (error, data) => {
if (error) {
return reject(error);
}
resolve(data);
});
});
test.then(data => { ... })
.catch(e => { ... })
});
@Not-Dan
Copy link

Not-Dan commented May 31, 2018

Thanks so much for not only answering the question but also walking me though this! I'll try this when I get home.

@Not-Dan
Copy link

Not-Dan commented Jun 1, 2018

Hi, This worked like a charm. I can't thank you enough!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment