我在Mongoose中使用findOne()
编写了一个函数,我想稍后将返回的结果用于另一个函数。我怎么能这样做?谢谢!
module.exports.findDeal = function(dealRequest){
Deal.findOne({name:dealRequest},function(err,newDeal){
if (err) throw err;
// twiml.message(newDeal.deal)
console.log("returned from the model: ",newDeal)
return
})
}
这是我后来打电话的功能
var newDeal = Deal.findDeal(dealRequest);
异步过程控制的典型问题,你应该使用promise或async / await,当然回调是好的,但不建议。
module.exports.findDeal = function(dealRequest, callback){ //callback function
Deal.findOne({name:dealRequest},function(err,newDeal){
if (err) callback(err)
console.log("returned from the model: ",newDeal)
callback(null, newDeal)
})
}
Deal.findDeal(dealRequest, (err, result) => { //callback function
var newDeal = result;
});
承诺风格:
module.exports.findDeal = function(dealRequest){
return new Promise((resolve, reject) => {
// still callback function is ok
Deal.findOne({name:dealRequest},function(err,newDeal){
if (err) reject(err)
resolve(newDeal)
})
// mongoose return promise, both is ok
Deal.findOne({name:dealRequest}).then(newDeal => {
resolve(newDeal)
}).catch(err => {
reject(err)
})
})
}
Deal.findDeal(dealRequest).then(result => {
var newDeal = result;
}).catch(err => {
console.log(err)
})
但我建议你使用async / await:
module.exports.findDeal = async function (dealRequest) {
return new Promise((resolve, reject) => {
try {
const newDeal = await Deal.findOne({name:dealRequest});
resolve(newDeal)
} catch (error) {
reject(error)
}
})
}
(async () => {
try {
var newDeal = await Deal.findDeal(dealRequest)
} catch (error) {
console.log(error)
}
})()
请注意,await必须在异步函数中使用并基于promise。
module.exports.findDeal = function(res,dealRequest){
Deal.findOne({name:dealRequest},function(err,newDeal){
if (err) throw err;
// twiml.message(newDeal.deal)
console.log("returned from the model: ",newDeal)
res.send({'result':newDeal});
})
}
在函数中添加res并使用res.send
你可以改用Promise。
那你的功能会是这样的。
module.exports.findDeal = function(dealRequest){
return Deal.findOne({name:dealRequest},function(err,newDeal){
if (err) throw err;
// twiml.message(newDeal.deal)
console.log("returned from the model: ",newDeal)
return newDeal;
})
在其他文件的某个地方
const { findDeal } = require('thisfilename.js');
findDeal(somdealvalue).then(function(deal) {
console.log(deal);
})
module.exports = {
findDeal: function(dealRequest){
return Deal.findOne({name:dealRequest},function(err,newDeal){
if (err) throw err;
// twiml.message(newDeal.deal)
console.log("returned from the model: ",newDeal)
return newDeal;
});
}
};
首先,将数据从内部函数返回到外部函数,然后从外部函数返回。