node.js mysql pool connection with async/ await

后端 未结 6 2094
清酒与你
清酒与你 2020-12-18 04:05

Is there a way to use pool.getConnection() taken from the mysqljs/mysql lib with the async/ await syntax?

The idea is to have a method whic

6条回答
  •  Happy的楠姐
    2020-12-18 04:40

    Previous answers (with util.promisify) did not work for me, and only implementing Promise manually works:

    Function:

    async function removeItem (id)  {
    
    return new Promise( (resolve) => {
        pool.query('DELETE FROM table_name WHERE id=' + id, (error) => {
              resolve ({result: !error});
            });
        }); 
    } 
    

    Usage:

    const app = express();
    const mysql = require('mysql');
    const pool = mysql.createPool({
                connectionLimit: 10,
                host: 'localhost',
                user: 'login',
                password: 'pass',
                database: 'dbname'
            });
    
    
    
    app.post("/:id", async (req, res) => {
            const answer = await itemRemove(id);
            res.send(answer);
        });
    

提交回复
热议问题