我使用Express with Node與MySQL數據庫進行交互。 我的Card對象的create
方法會將數據保存到數據庫,並應更新對象的id爲查詢返回的insertId。使用Promise的值更新對象屬性
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)。
我玩過幾種不同的方法來試圖捕獲id,用新值設置對象的id屬性,並將該值保存到對象中。然而,它似乎總是被更新的卡的本地範圍版本,而不是原始卡(打印到頁面)。
使用Promise時,指定對象數據並返回對象實例的適當位置是什麼?
請問您的卡表必須用'AUTO_INCREMENT'關鍵屬性? – trincot
你真的將一個承諾('card.create()')的返回值傳遞給'res.json'嗎?我不知道怎麼有一個'.id'。 – Bergi