【问题标题】:Object called undefined in inner nested Callback function内部嵌套回调函数中调用未定义的对象
【发布时间】:2017-06-21 12:35:03
【问题描述】:

"First" 与 Object t 一起打印,但在输入 Callback 之后的 Callback 与 t 一起打印为 undefined。在 Applied(t) 函数中,由于 Object t 出于某种原因此时未定义,因此会导致错误 -TypeError: Cannot read property '_id' of undefined-。如果在进入此回调函数之前没有未定义,这可能是什么原因? 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);
        });

    });


}

【问题讨论】:

  • 您有太多名为t 的变量。给他们唯一的名字。就此而言,请停止使用 1 和 2 个字母的变量名称,并为所有变量提供有意义的名称。
  • 所以第二次更新失败,显然t不是你想的那样

标签: javascript node.js mongodb


【解决方案1】:

对象 t 出于某种原因此时未定义。如果在进入此回调函数之前没有未定义,这可能是什么原因? update() 是一个 MongoDB 函数。

原因是您的第一个回调(和第二个)中的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);
                }
            );
        }
    );
}

【讨论】:

  • 我正在尝试使用 Object t 作为第二个回调函数的参数。如果我创建一个参数 t2,那么我将不会从 t 获得我需要的数据。
  • @AaronReich 更新了我的答案。
猜你喜欢
  • 2018-09-11
  • 2015-11-23
  • 2019-12-16
  • 2017-01-28
  • 1970-01-01
  • 1970-01-01
  • 2021-01-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多