Skip to content

Instantly share code, notes, and snippets.

@AMD-NICK
Last active June 23, 2023 20:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AMD-NICK/bd08bbf7fd3ab6fe8cd2565ea40225c0 to your computer and use it in GitHub Desktop.
Save AMD-NICK/bd08bbf7fd3ab6fe8cd2565ea40225c0 to your computer and use it in GitHub Desktop.
Play with lua coroutines. Make async http function synchronous
-- idea source: https://luyuhuang.tech/2020/09/13/callback-to-coroutine.html
-- Async request demo
--[[ http.Fetch("https://httpbin.org/get?a=b&c=d", function(code, content)
print("code, content", code, content)
end, function(err)
print("Error", err)
end, {
header_asd = "qwe"
})
]]
local function coroutinize(f, ...)
local co = coroutine.create(f)
local function exec(...)
local ok, data = coroutine.resume(co, ...)
if not ok then
error(debug.traceback(co, data))
end
if coroutine.status(co) ~= "dead" then
data(exec)
end
end
exec(...)
end
local function http_fetch_sync(url, headers)
return coroutine.yield(function(cb)
http.Fetch(url, function(...)
cb({resolve = {...}})
end, function(...)
cb({reject = {...}})
end, headers)
end)
end
coroutinize(function()
local res = http_fetch_sync("https://poll.gmod.app/asd?sleep=3")
PRINT("data received 1:", util.JSONToTable(res.resolve[1]))
local res = http_fetch_sync("https://httpbin.org/get?a=b&c=d")
PRINT("data received 2:", util.JSONToTable(res.resolve[1]))
local res = http_fetch_sync("https://poll.gmod.app/asd?sleep=3")
PRINT("data received 3:", util.JSONToTable(res.resolve[1]))
end)
@AMD-NICK
Copy link
Author

local http_get = require("http_async").get -- http.Fetch

local function fetch(url)
	local th = coroutine.running()
	
	http_get(url, function(a, b, c, d)
		coroutine.resume(th, {a = a, b = b, c = c, d = d})
	end, function(err)
		coroutine.resume(th, {err = err})
	end)

	return coroutine.yield()
end

local function fetch_all_urls(cb)
	coroutine.wrap(function()
		local res1 = fetch("https://httpbin.org/get")
		local res2 = fetch("https://httpbin.org/get")
		local res3 = fetch("https://httpbin.org/get")
		cb({res1, res2, res3})
	end)()
end

fetch_all_urls(fp{PRINT, "hello"})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment