在内部嵌套的回调函数中调用未定义的对象

问题描述:

“第一个”与正在打印的对象t一起打印,但输入该回调后的回调“第二个”与t被打印为未定义一起打印。在应用的(t)函数中,错误-TypeError:无法读取undefined-的属性'_id',这是因为Object t由于某种原因在此处未定义。如果在进入此回调函数之前没有定义,可能是什么原因? update()是一个MongoDB函数。在内部嵌套的回调函数中调用未定义的对象

function applied(t) 
{ 
    this.transactions.update(
    { 
     _id: t._id, state: "pending" }, 
    { 
     $set: { state: "applied" }, 
     $currentDate: { lastModified: true } 
    } 
) 
} 

function applytransaction(t,f,fb) 
{ 

    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 } } 
    , function(err,t,y) { 
     console.log("First "+t); 
     this.model.update(
      { _id: t.destination, pendingTransactions: { $ne: t._id } }, 
      { $inc: { bal: y }, $push: { pendingTransactions: t._id } } 
     , function(err, t) { 
      console.log("Second " +t); 
      applied(t); 
     }); 

    }); 


} 
+0

您有太多名为't'的变量。给他们独特的名字。对于这个问题,停止使用1和2个字母的变量名称并给所有变量赋予有意义的名称。 – JLRishe

+0

所以第二次更新失败,很明显't'不是你认为它是 – adeneo

Object t is for some reason undefined at this point. What could be the cause of this if it was not undefined prior to entering this Callback function? update() is a MongoDB function.

的原因是第一个回调内部的t(和第二个)是从该第一t不同。给他们独特的名字并检查错误,你应该找出问题所在。

根据您的意见更新:如果您想在整个功能中使用原始的t,那么就使用它。不要指望它以某种方式出来的回调参数,因为according to the docs,传递给回调的第二个值是更新的记录数,而不是t是。

function applytransaction(t, f, fb) 
{ 
    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 } }, 
     function(err1, count1, status1) { 
      console.log("First err:", err1); 
      console.log("First ", t); 

      this.model.update(
       { _id: t.destination, pendingTransactions: { $ne: t._id } }, 
       { $inc: { bal: y }, $push: { pendingTransactions: t._id } }, 
       function(err2, count2) { 
        console.log("Second err", err2); 
        console.log("Second ", t); 

        applied(t); 
       } 
      ); 
     } 
    ); 
} 
+0

我试图使用Object t作为第二个回调函数的参数。如果我创建一个参数t2,那么我将不会从t中获得所需的数据。 –

+0

@AaronReich更新了我的答案。 – JLRishe