类属性不更新

我有一个.js对象的属性,当我问我时,它不会更新。

我是新的JavaScript世界,所以我希望我的问题不会太棘手。

首先,这是我的Node类的一部分:

Node = function (label, vals, db, callback) { // attributes this.label = label; this.vals = vals; this.db = db; if (typeof calback == 'function') calback(); } Node.prototype.insert_db = function (calback) { var vals = this.vals; // Create a node console.log("1:"); // output print console.log(vals); // output print this.db.save(vals, function (err, node) { if (err) throw err; vals = node; console.log("2:"); // output print console.log(vals); // output print }); this.vals = vals; console.log("3:"); // output print console.log(this.vals); // output print if (typeof calback == 'function') calback(); } 

我想用这个代码来做的事是在插入后更新我的Node对象的“id”值。 但是…这是我的console.log运行这个代码后:

 var per = new Node('Whatever', { firstName: "aaaa", lastName: "aaaa", age: "aaaa" }, db2); per.insert_db(); 

控制台输出:

 1: { firstName: 'aaaa', lastName: 'aaaa', age: 'aaaa' } 3: { firstName: 'aaaa', lastName: 'aaaa', age: 'aaaa' } 2: { firstName: 'aaaa', lastName: 'aaaa', age: 'aaaa', id: 491 } 

第三个状态(第二个状态)永远不会更新。 我不知道它来自哪里。 我在这个问题上花了两天时间,显然我已经无法处理了。

提前致谢。

编辑仍然有麻烦。 感谢@MarkHughes,这是我的新代码

 Node.prototype.insert_db = function (callback) { var temp = this; this.db.save(this.vals, function (err, node) { if (err) throw err; temp.vals = node; console.log(temp.vals); // output print if (typeof callback == 'function') callback(); }); } 

代码由此运行

 var per = new Node('Person', { firstName: "aaaa", lastName: "aaaa", age: "aaaa" }, db2); per.insert_db(res.render('login-index', { title: 'miam', dump: mf.dump(per) })); 

现在这里是console.log(temp.vals)

 { firstName: 'aaaa', lastName: 'aaaa', age: 'aaaa', id: 515 } 

这里是呈现的输出(pre html):

 vals: object(3): { firstName: string(4): "aaaa" lastName: string(4): "aaaa" age: string(4): "aaaa" } 

输出是asynchronous函数的callback函数.save …而且还没有更新。 🙁

我不知道这是否有帮助,仅用于debugging:

 setTimeout(function() { console.log(temp) }, 3000); 

.save函数之后写入,返回:

 [...] vals: { firstName: 'aaaa', lastName: 'aaaa', age: 'aaaa', id: 517 }, [...] 

我究竟做错了什么 ?

.save是asynchronous的,所以你不能在callback之外使用它所返回的值,因此在callback中移动你的代码的其余部分将修复它:

 var t = this; this.db.save(vals, function (err, node) { if (err) throw err; vals = node; console.log("2:"); // output print console.log(vals); // output print t.vals = vals; console.log("3:"); // output print console.log(t.vals); // output print if (typeof calback == 'function') calback(); }); 

将“this”保存到variables允许从callback内部访问它。

对于你的调用代码,你需要确保你正在从insert_db()callback输出,例如:

 per.insert_db(function () { res.render('login-index', { title: 'miam', dump: mf.dump(per) }) }); 

请注意,您必须将res.render包装到函数()中,否则将传入的内容是callback函数的返回值,而不是函数本身。