Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

app.use(async function(req, res, next) {
    try {
        var myres = await new Promise((resolve, reject) => {
            mysql_connection.query("select * from Users;", (err, rows) => {
                if (err) {
                    reject(err);
                } else {
                    resolve(rows);
                }
            });
        });
    } catch (error) {
        console.log(error);
    }
});

Question is. using async function to be able to use await for DB queries is ok? i am afraid that it can cause some problems on expressjs side.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
299 views
Welcome To Ask or Share your Answers For Others

1 Answer

async..await is syntactic sugar for promises, and a promise is just a pattern that relies on callbacks. The use of async functions is acceptable wherever they are supported by the environment. async..await is supported since Node.js 7.6.0.

async function always returns a promise. As long as this implicit return value doesn't cause problems, it's perfectly fine everywhere, including Express. It doesn't matter whether it's used for database queries or anything else.

Unless API supports promises, errors should be entirely handled in async function. Function body should be wrapped with try..catch to rule out unhandled rejections which may result in exceptions in future Node versions.

The original code contains no next calls and just suppresses an error. As a rule of thumb, async middleware should be structured like that:

app.use(async function(req, res, next) {
    try {
        ...
        next();
    } catch (error) {
        next(error);
    }
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...