Return from Websockets.open do block

I have a scenario in which I’m intentionally sending a wrong message to a websocket and it returns me the right input; I need to parse and store the right input and use it across the application. But I can’t return it. Here’s what the code looks like right now:

rightmsg = WebSockets.open(url) do ws 
                            wrongmsg = generatewrongmsg()
                            if writeguarded(ws, JSON3.write(wrongmsg)
                               data, success = readguarded(ws)
                               # parse data here 
                               return data
                           end 
                  end

But it just returns a HTTP.Messages.Response object. I can assign it to a global, but this block is not in a global scope; it’s inside a function and Julia doesn’t seem to have a way to capture a non-global, local variable. Any solution?

Ok I figured out a solution. Just need to write to a 1-sized Channel and then return with take!(ch). Still feels a bit tacky.

1 Like

See the docs for the global keyword arg too: Essentials · The Julia Language

Does this work in non-global contexts? What I have is:

function socketstuff()
       local rightmsg # It had to be local cuz naming conflicts in the global scope (for API reasons)
       WebSockets.open(url) do ws 
                            wrongmsg = generatewrongmsg()
                            if writeguarded(ws, JSON3.write(wrongmsg)
                               data, success = readguarded(ws)
                               # parse data here 
                               global rightmsg = data ### Am I even doing right???
                           end 
                  end