javascript - 使用 Promise 的值更新对象属性

标签 javascript object asynchronous promise

我使用 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/

相关文章:

java - 使用 "Object"关键字在 Java 中创建对象

javascript - 如何使用 q.js Promise 处理多个异步操作

java - 从 HTTP 调用时 URL 返回 504 错误

javascript - 当 Label.text 无法处理大小(内存不足)时,如何在 asp.net 中附加大 Html 字符串

javascript - Bootstrap 行类每个第三个元素与 vue 模板

javascript - 在模态弹出窗口或标准弹出窗口中打开 Facebook Share

javascript - 如何基于两个数组创建数组

javascript - 鼠标滚动卡住 chrome 选项卡

python - 关于 numpy 沿轴应用和列表理解的困惑

javascript - Node JS 中的事件循环阻塞和异步编程