我使用 Express 和 Node 与 MySQL 数据库交互。
我的 Card 对象的 create
方法会将数据保存到数据库,并应将对象的 id 更新为从查询返回的 insertId。
class Card {
constructor(d) {
this.id = d.id || 0;
this.playerId = d.playerId;
this.drawn = false;
this.title = d.title
this.qty = d.qty;
this.hint = d.hint;
this.type = d.type;
this.descr = d.descr;
this.pair = d.pair
this.data = d;
}
create(conn) {
return new Promise( (resolve, reject) => {
var query = "INSERT INTO cards SET ? ";
conn.query(query, this.data, function(err, result) {
if (err) throw err;
(typeof result.insertId === 'number')
? resolve(result.insertId)
: reject("Failed to insert a new Card.");
resolve(result.insertId);
})
}).then( (id) => {
this.id = id;
console.log("Your insert id is");
console.log(this.id) // GREAT! It prints the correct id
return this; // Set the value of the promise to this Card instance
})
}
}
创建卡片后,它应该打印卡片的 json 表示形式。
router.post('/create-card', function(req, res) {
var data = req.body;
var card = new Card(data);
card = card.create(db.connection);
res.json(card);
})
但是返回对象的id
始终是默认值(0)。
我尝试了几种不同的方法来 try catch id、使用新值设置对象的 id 属性并将该值保留到对象。然而,它似乎总是更新的卡的更本地范围的版本,而不是原始卡(打印到页面上)。
使用 Promises 时,分配对象数据并返回对象实例的正确位置是什么?
最佳答案
您过早调用 res.json
。您需要等待 promise 的解决方案:
card.create(db.connection).then( _ => res.json(card));
关于javascript - 使用 Promise 的值更新对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47490786/