How can I get data returned from an event?

Hi, I am testing and learning to make my own resources. I was testing how to interact with a DB, and I get it to work. But the problem was when I tried to return the data.

I have this:

Server File → (server.lua)

In this file I have created a NetEvent to be able to use it in a client-side script. This event gets the DB data I want and is supposed to return it. But instead of returning what it should (false, in this case), it returns a number. I have tested it and the data is extracted from the DB correctly, the problem is when I try to return it to the client-side script. This is what I have:

RegisterNetEvent("test_net_event")
AddEventHandler("test_net_event", function(arg1)
    MySQL.Async.fetchAll( --here would be the SQl query,
    function(result)
        data = result[1].field_name
    end)
    return data
end)

Client File → (client.lua)

local data_returned = TriggerServerEvent("test_net_event", arg)

In this file I am calling the NetEvent Created in the server.lua file, to get the DB data.

Finally, if I try printing the data_returned variable (print(data_returned)) it shows a number and not the DB data I wanted. How can I solve this? Am I doing anything wrong?

Thanks in advance.

You’d have to study callbacks to implement something like this, I’m gonna give you an example.

RegisterNetEvent("test_net_event")
AddEventHandler("test_net_event", function(args, cb)
    -- args is a table
    MySQL.Async.fetchAll(--here would be the SQl query,
    function(result)
        -- Maybe a sanity check??
        data = result[1].field_name
    end)
    cb(data) -- Here you pass data as a parameter on callback (cb)
end)

TriggerServerEvent("test_net_event", { arg },
function(data) -- this is our callback, with the parameter
    -- do whatever with data
end)

I believe the number is your player source. Net events return an extra parameter (player source) prepended to your data, essentially, so you know which client the event originated from.

Try changing

AddEventHandler("test_net_event", function(arg1)

to

AddEventHandler("test_net_event", function(source, arg1)

arg1 should now reflect your intended data;

Source is provided as a global variable, adding it as a function argument won’t do anything besides making arg1 be under the wrong variable name.

Regarding the actual question, you would have to make a system to actually send a callback to the client with the data, but note you cannot use function callbacks as you can’t share a function across server/client, you can use something like pmc-callbacks for this

Also note: since you’re using MySQL async you would need to use promises to wait for the data, or convert it to a Sync call, otherwise data will be nil.

lol, yea, this is what I get for trying to answer this stuff at 4am, after 6 months of being away from my computer… :man_facepalming:t4: