Node.JScallback函数没有被执行

settopending(f,fb)是第一个调用的函数,我不确定是否没有正确写callback函数,因为applytransaction(t,f,fb)永远不会被调用。 打印“第一”和“第二”,但不打印“第三”和“第四”。 我是否错误地设置了应该调用applytransaction(t,f,fb)的callback,还是有其他问题呢?

function update(document,f,fb) { this.transactions.update( { _id: document._id, state: "initial" }, { $set: {state: "pending"}, $currentDate: {lastModified: true} } ); console.log("Second") } function settopending(f,fb) { console.log("First"); var t = this.transactions.findOne( { state: "initial" } , function(err, document) {//CALLBACK update(document,f,fb , function(err, document) {//CALLBACK console.log("Third"); applytransaction(document,f,fb); }); }); } function applytransaction(t,f,fb) { console.log("Fourth"); x=fb(t.value); y=f(t.value); this.model.update( { _id: t.source, pendingTransactions: { $ne: t._id } }, { $inc: { bal:x }, $push: { pendingTransactions: t._id } } ); this.model.update( { _id: t.destination, pendingTransactions: { $ne: t._id } }, { $inc: { bal: y }, $push: { pendingTransactions: t._id } } ) } 

作为一个纯粹的猜测,如果this.transactions.update接受callback

 function update(document, f, fb, cb) { // added cb parameter this.transactions.update({ _id: document._id, state: "initial" }, { $set: {state: "pending"}, $currentDate: {lastModified: true} }, cb // added cb argument ); console.log("Second") } 

尽pipe如ffb所不需要的更新

 function update(document, cb) { this.transactions.update({ _id: document._id, state: "initial" }, { $set: {state: "pending"}, $currentDate: {lastModified: true} }, cb ); console.log("Second") } function settopending(f,fb) { console.log("First"); var t = this.transactions.findOne( { state: "initial" } , function(err, document) {//CALLBACK update(document, function(err, document) {//CALLBACK console.log("Third"); applytransaction(document,f,fb); }); }); } 

更有意义

问题是你的更新方法。 你不是在调用fb(任何地方的callback方法)。 在这个操作“this.transactions.update”之后,该方法就不需要调用传递的callback函数了。

之后添加一个函数调用:fb(err,document);

 function update(document,f,fb) { this.transactions.update( { _id: document._id, state: "initial" }, { $set: {state: "pending"}, $currentDate: {lastModified: true} } ); console.log("Second") } 

大多数情况下,这个“this.transactions.update”也会期待callabck方法。 你需要把你的逻辑如下所示:

 function update(document,f,fb){ this.transactions.update( { _id: document._id, state: "initial" }, { $set: {state: "pending"}, $currentDate: {lastModified: true} },function(err,doc){ if(err){ fb(err,null) }else{ fb(null,doc) } } ); console.log("Second") 

}

 function update(document,f,fb, callback) { this.transactions.update( { _id: document._id, state: "initial" }, { $set: {state: "pending"}, $currentDate: {lastModified: true} }, callback(); ); console.log("Second") } 

您还需要在此函数中具有callback参数,然后在事务完成时发送callback()。