Created
May 31, 2018 09:29
-
-
Save AlexBHarley/236fa23b9b39f96446f1d60beece01fc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 => { ... }) | |
}); |
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
Thanks so much for not only answering the question but also walking me though this! I'll try this when I get home.