在内部嵌套回调函数

时间:2017-02-04 03:18:45

标签: javascript node.js mongodb

打印“第一个”,同时正常打印对象t但输入回调后的回调“打印第二个”,同时打印为未定义。在applied(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);
        });

    });


}

1 个答案:

答案 0 :(得分:0)

  

对象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);
                }
            );
        }
    );
}
相关问题