Synchronously fetch data from the DB

Hello everyone!

I know we can easily fetch data from the database asynchronously using the mysql-async library, but this time I really want to do it synchronously, or at least do something to wait for asynchronous code to execute in full. Is this possible? Here’s a bit of code you can base it on.

NOTE: This code is for exemplification purposes only and is not complete!

MySQL.ready(function()
    print("before query")
    MySQL.Async.fetchAll("SELECT * FROM mytable WHERE id = @id", { ["@id"] = id }, function(result)
        if result[1] then
            print("sucess")
            local username = result[1].username
        else print("no user found") end
    end)
    print("after query")
    if username then print("username", username) end
end)

I’ve tried doing it with MySQL.Sync.fetchAll, but FiveM just ignores it and skips it.

Any options/opinions are welcome!
Thanks for reading! :smile:

I dont use mysql-async and would advise making the switch to OxMySQL.

but in your example you can do something like

MySQL.ready(function()
    local p = promise.new()
    MySQL.Async.fetchAll("SELECT * FROM mytable WHERE id = @id", { ["@id"] = id }, function(result)
        p:resolve(result)
    end)
    local result = Citizen.Await(p)
    if result[1] then
        print("sucess")
        local username = result[1].username
        print("username", username)
    else
        print("no user found")
    end
end)
1 Like

I will definitely switch to oxmysql. I didn’t test your example, but with the oxmysql promise I got the result I wanted.

Thanks for the help! :smile:

For those who are interested, here is the resolution of my problem using oxmysql.

NOTE: This code is for exemplification purposes only and is not complete! Assuming that oxmysql is already installed and configured.

print("before query")

local result = MySQL.query.await("SELECT * FROM mytable WHERE id = ?", { id })
if result then
    print("success")
    local username = result[1].username
else print("no user found") end

print("after query")
if username then print("username", username) end