Moongose中的回调函数

Callback function in Moongose

本文关键字:函数 回调 Moongose      更新时间:2023-09-26

是否有任何方法可以在带有回调函数的函数中返回值?

function getnextseq(){    
 autoincrement.findOneAndUpdate({ _id:"userid"}, { $inc: { seq:1}},function(err,data){
console.log(data.seq)
})
return data.seq;
}
console.log(getnextseq());

简单地返回data.seq将不起作用,因为findOneAndUpdate是异步的。您需要传递回调函数或使用promise

function getnextseq(cb) {    
 autoincrement.findOneAndUpdate({ _id:"userid"}, { $inc: { seq:1}},function(err,data){
   cb(data.seq);
 })
}
getnextseq(function(seq) {
   console.log(seq);
 }
);

或承诺方式

 function getnextseq() {    
    return autoincrement.findOneAndUpdate({ _id:"userid"}, { $inc: { seq:1}}).exec();
 }

 getnextseq().then(function(seq) {
   console.log(seq)
 });