异步等待承诺的数据在快速 POST 调用时不可用

问题描述 投票:0回答:1

我是异步编程的新手,并试图了解以下内容:

以下代码 //DB Load Users 工作正常 //New user to DB 之后的代码确实将新用户写入 mysql DB,但无法在呈现之前刷新用户中的数据。 网络服务器挂起(光标计时器符号),当我重新输入 url 时,页面呈现,但没有新数据。只有重新启动终端才能使网页上的数据可用。

//DB Load Users
const users = new Promise((resolve, reject) => {
    var sql = "SELECT username, useremail, userage, useruniqueid FROM users";
    db.query(sql, function(err, result) {
        if (err) throw err;
        resolve(result);
    });
})

//DB refresh Users
function refresh() {
    const users = new Promise((resolve, reject) => {
        var sql = "SELECT username, useremail, userage, useruniqueid FROM users";
        db.query(sql, function(err, result) {
            if (err) throw err;
            resolve(result);
        });
    })
}


//Render (express) HTML with promise resolve after DB-query - works!!
app.get("/", async(_req, res, next) => {
    try {
        res.render("home", { data: await users });
    } catch (err) {
        next(err);
    }
});



//New user to DB
app.post("/", (req, res) => {
    const inputUserName = req.body.username
    const inputUserEmail = req.body.useremail
    const inputUserAge = req.body.userage
    const inputUserUniqueId = req.body.useruniqueid

    db.query('insert into users values(?,?,?,?)', [inputUserUniqueId, inputUserName, inputUserEmail, inputUserAge], (err, result) => {
        if (err) { console.log(err) } else {
            console.log('new user added');
        }
    })
    refresh(); //update users from DB
    // wait for user-data and render webpage - does not work - no updated data and webserver hangs
    app.get("/", async(_req, res, next) => {
        try {
            res.render("home", { data: await users });
        } catch (err) {
            next(err);
        }
    });
})

当我使用手动定义的用户 [] 时,我让网络服务器端完全运行,将新条目推送到数组的末尾。所以我假设这是我对这里的异步时间缺乏理解。

mysql node.js express asynchronous async-await
1个回答
0
投票

问题是您的范围界定:

const users
无法更改(因此:常量),即使您尝试更改,您也将其范围限定为
refresh
函数,这意味着它不会得到更新,即使您的查询正确运行。这是应该按预期工作的代码:

// Make users replacable by using `let`, which can be changed.
let users = new Promise((resolve, reject) => {
    var sql = "SELECT username, useremail, userage, useruniqueid FROM users";
    db.query(sql, function(err, result) {
        if (err) throw err;
        resolve(result);
    });
})

function refresh() {
   // You want to assign this new promise to the global `users` variable.
   // If you set a constant here, the result will only be
   // available within this function scope.
   // But because the global object is `let`, we can reassign it from within here.
   // Just don't _declare_ it here, only reassign it.
   users = new Promise((resolve, reject) => {
        var sql = "SELECT username, useremail, userage, useruniqueid FROM users";
        db.query(sql, function(err, result) {
            if (err) throw err;
            resolve(result);
        });
    })
}
© www.soinside.com 2019 - 2024. All rights reserved.