[英]Class atributes not updating [node.js - express ]
我对.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"
}
输出在回调函数中,而在异步函数.save
,并且仍然没有更新。 :(
我不知道这是否有帮助,仅用于调试:
setTimeout(function() { console.log(temp) }, 3000);
.save
函数之后编写的代码返回以下内容:
[...]
vals: { firstName: 'aaaa', lastName: 'aaaa', age: 'aaaa', id: 517 },
[...]
我究竟做错了什么 ?
.save是异步的,因此您不能在其回调之外使用它返回的值,因此将其余代码移到回调内将对其进行修复:
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”保存到变量中可以从回调内部对其进行访问。
对于您的调用代码,您需要确保要在insert_db()的回调中呈现输出-例如:
per.insert_db(function () {
res.render('login-index', { title: 'miam', dump: mf.dump(per) })
});
请注意,必须将res.render包装在function()中,否则将作为回调传递的内容是执行该函数的返回值,而不是函数本身。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.