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 hidden or 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) |
Author
AMD-NICK
commented
Jun 23, 2023
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment