异步等待回调函数

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

我有这个功能可以将用户保存在数据库中:

exports.saveUser = ({ first_name, last_name, email, password }) => {
    const query = "insert into users (first_name, last_name, email, password_hash) values ($1, $2, $3, $4) RETURNING *";
    bcrypt.hash(password, 10, async function (err, hash) {
        const res = await db.query(query, [first_name, last_name, email, hash]);
        return res.rows[0];
    });
    return res;
};

我在 bcrypt 回调中有异步函数,其中发生插入以及我返回插入的行。我如何让它返回 saveUser 函数?

所以最后

saveUser()
会是那个
res.rows[0]
记录吗?

javascript node.js express asynchronous async-await
1个回答
1
投票
exports.saveUser = async ({ first_name, last_name, email, password }) => {
    const query = "insert into users (first_name, last_name, email, password_hash) values ($1, $2, $3, $4) RETURNING *";
    let hash = await bcrypt.hash(password, 10);
    const res = await db.query(query, [first_name, last_name, email, hash]);
    return res.rows[0];
};
© www.soinside.com 2019 - 2024. All rights reserved.