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
但是service_id是一个承诺,所以查询是不对的,我不想在回调中调用回调模型等等,我尝试过异步
async.series([getVariables], function(err, results){
otherSchema.findOne({service : service_id}).exec(...)})
Where getVariables is :
getVariables在哪里:
function getVariables(callback1) {
if(service_id!=undefined) {
callback1(serviceID)
}}
Any help on how to achieve this is more than welcome! thanks a lot
任何关于如何实现这一点的帮助都是非常受欢迎的!非常感谢
2 个解决方案
#1
2
try this exec()
returns promise.
试试这个exec()返回承诺。
serviceSchema.statics.getIdByName = function getIdByName(serviceName) {
return this.findOne({
name: serviceName
}).exec();
}
Call getIdByName function
调用getIdByName函数
Service.getIdByName("facebook").then((data) => {
console.log(data)
})
#2
0
The answer to this is actually using async/await and and do var x = await Model.findOne().exec()
答案实际上是使用async/ wait和do var x = wait Model.findOne().exec()
or any function that returns a promise, then you can use x anywhere in the code
或者任何返回承诺的函数,然后你可以在代码的任何地方使用x
#1
2
try this exec()
returns promise.
试试这个exec()返回承诺。
serviceSchema.statics.getIdByName = function getIdByName(serviceName) {
return this.findOne({
name: serviceName
}).exec();
}
Call getIdByName function
调用getIdByName函数
Service.getIdByName("facebook").then((data) => {
console.log(data)
})
#2
0
The answer to this is actually using async/await and and do var x = await Model.findOne().exec()
答案实际上是使用async/ wait和do var x = wait Model.findOne().exec()
or any function that returns a promise, then you can use x anywhere in the code
或者任何返回承诺的函数,然后你可以在代码的任何地方使用x