Last active
June 23, 2023 20:50
-
-
Save AMD-NICK/bd08bbf7fd3ab6fe8cd2565ea40225c0 to your computer and use it in GitHub Desktop.
Play with lua coroutines. Make async http function synchronous
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- 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) |
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
Связь: https://gist.github.com/AMD-NICK/0fc6a36f87e0232e5d1a9dd60b864e18?permalink_comment_id=4462357#gistcomment-4462357