Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
local co
local fetch = function(url)
local promise = js.global:fetch(url)
promise["then"](promise, function(_, res)
local jsonPromise = res:json()
jsonPromise["then"](jsonPromise, function(_, json)
co(json)
end)
end)
local res = coroutine.yield()
return res
end
local fetchAll = function(...)
local requests = {...}
for i = 1, #requests do
local promise = js.global:fetch(requests[i])
promise["then"](promise, function(_, res)
local jsonPromise = res:json()
jsonPromise["then"](jsonPromise, function(_, json)
co(i, json)
end)
end)
end
local results = {}
for i = 1, #requests do
local requestId, response = coroutine.yield()
results[requestId] = response
end
return results
end
co = coroutine.wrap(function()
local bird1 = fetch("http://apiv3.iucnredlist.org/api/v3/species/loxodonta%20africana?token=9bb4facb6d23f48efbf424bb05c0c1ef1cf6f468393bc745d42179ac4aca5fee")
local bird2 = fetch("http://apiv3.iucnredlist.org/api/v3/species/Fratercula%20arctica/region/europe?token=9bb4facb6d23f48efbf424bb05c0c1ef1cf6f468393bc745d42179ac4aca5fee")
print("Sequential: ", bird1.name, bird2.name)
local birds = fetchAll(
"http://apiv3.iucnredlist.org/api/v3/species/loxodonta%20africana?token=9bb4facb6d23f48efbf424bb05c0c1ef1cf6f468393bc745d42179ac4aca5fee",
"http://apiv3.iucnredlist.org/api/v3/species/Fratercula%20arctica/region/europe?token=9bb4facb6d23f48efbf424bb05c0c1ef1cf6f468393bc745d42179ac4aca5fee"
)
print("Parallel: ")
for i = 1, #birds do
print(birds[i].name)
end
end)
co()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.