Reputation: 53
I am trying to get a good understanding of how to work with promises, mostly because I want to query data and then use that data to query other data
I have this Schema :
var serviceSchema = new Schema({
name: String,
});
And this method on it :
serviceSchema.statics.getIdByName = function getIdByName (serviceName) {
this.findOne({name :serviceName }).exec(function(err, service){
if(err) console.log(err)
return service._id
})
}
In my code I would like to do something like :
var service_id = Service.getIdByName("facebook")
otherSchema.findOne({service : service_id}).exec(...)
but service_id is a promise so the query isn't right, I don't want to be in callback hell and calling models inside of callbacks etc I have tried async with something like
async.series([getVariables], function(err, results){
otherSchema.findOne({service : service_id}).exec(...)})
Where getVariables is :
function getVariables(callback1) {
if(service_id!=undefined) {
callback1(serviceID)
}}
Any help on how to achieve this is more than welcome! thanks a lot
Upvotes: 2
Views: 111
Reputation: 53
The answer to this is actually using async/await and and do var x = await Model.findOne().exec()
or any function that returns a promise, then you can use x anywhere in the code
Upvotes: 0
Reputation: 10071
try this exec()
returns promise.
serviceSchema.statics.getIdByName = function getIdByName(serviceName) {
return this.findOne({
name: serviceName
}).exec();
}
Call getIdByName function
Service.getIdByName("facebook").then((data) => {
console.log(data)
})
Upvotes: 2