Search code examples
node.jspromisemysql2

Error occurs on promise in node.js looking to make this a promised connection and fix


await conn.query("SELECT ID, idle_timer, action, combat FROM users WHERE idle_timer >= 1 ORDER BY ID ASC", async function(err, results) {
    }

error occurs at await conn.query("SELECT ID, idle_timer, action, combat FROM users WHERE idle_timer >= 1 ORDER BY ID ASC", async function(err, results) {

looking to convert this to a promise?


Solution

  • You could use MySQL for fetching data

    in callback mode

    conn.query("SELECT ID, idle_timer, action, combat FROM users WHERE idle_timer >= 1 ORDER BY ID ASC", function(err, results) {...})
    

    or in the Promise mode

    conn.query("SELECT ID, idle_timer, action, combat FROM users WHERE idle_timer >= 1 ORDER BY ID ASC").then(results => { ... })
    

    or maybe in Promise mode with Await/Async syntax sugar

    const result = await conn.query("SELECT ID, idle_timer, action, combat FROM users WHERE idle_timer >= 1 ORDER BY ID ASC")
    
        //...
        const results = await conn.query("SELECT ID, idle_timer, action, combat FROM users WHERE idle_timer >= 1 ORDER BY ID ASC");
        await conn.release();
    
        for (let i = 0; i < results.length; i++) {
            //... processing results
        }
    

    if you new to async/await please read about promises, at least https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Statements/async_function