1

I have an issue while I go through this function. It doesn't render values in the good order. I tried to use async/await, but maybe I'm not using it in proper way. Here db is for mySQL.

   function getUserInfo() {
    db.connect(function (err) {
        if (err) throw err;
        db.query("SELECT id FROM game WHERE id = '" + authorId + "'", function (err, result, field) {
            if (result.length === 0) {
                var sql = "INSERT INTO game (id, user, coins) VALUES (" + authorId + ", '" + authorName + "', 0)";
                db.query(sql, function (err, result) {
                    if (err) throw err;
                    console.log("Données enregistré");
                    result = 0
                    return new Promise((resolve) => {
                        if (true) {
                            resolve(result);
                        }
                    })
                });
            } else {
                var sql = "SELECT coins FROM game WHERE id = " + authorId + "";
                db.query(sql, function (err, result) {
                    if (err) throw err;
                    console.log(result[0].coins);
                    return new Promise((resolve) => {
                        if (true) {
                            resolve(result[0].coins);
                        }
                    })
                });
            }
        })
    });
}

async function operationAsync() {
    const result = await getUserInfo()
    console.log(result)
}

operationAsync()

I have this result:

undefined
Données enregistré

I want the first function to be done before trying to display his result.

Any idea ?

  • Whatever `db` is (probably `mysql` or similar) is not using promises. It instead uses an older style _callback_ mechanism. The `mysql2` library supports promises as do other abstractions like Sequelize – Phil Feb 02 '22 at 22:09
  • What's `db`? Maybe that API already returns promises which can be `await`ed? – Jonas Wilms Feb 02 '22 at 22:09
  • Slapping `async` on a function doesn't make it magically detect asynchronous callback and allow to `return` from them. You need to work with promises. – Bergi Feb 02 '22 at 22:10
  • async/await requires a promise returned from the function, and await can be called inside async context only read more here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function – skmail Feb 02 '22 at 22:11
  • 1
    Btw, you also have a severe security issue with sql injections. Use parameterised queries! – Bergi Feb 02 '22 at 22:11
  • assuming `db` is not a promise, wrap a promise in the `getUserInfo` functionality and `resolve` it with the data you're looking from the callbacks you are using – justinw Feb 02 '22 at 22:11

0 Answers0