我遇到了一些问题,一个.js对象的atribute在我要求它更新时没有更新。
我是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
中的<strong。。。仍然没有更新。:(>
我不知道这是否有帮助,仅用于调试:
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((中,否则作为回调传递的将是执行该函数的返回值,而不是函数本身。