Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Calculator

0

52
Views
Async/await issue, it's not returning the data I want

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 ?

7 months ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2023 PeakU Inc. All Rights Reserved.