Skip to content

Instantly share code, notes, and snippets.

@giann
Created July 25, 2017 05:54
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save giann/6a1cc45e36dd10afae30744f9b8193ac to your computer and use it in GitHub Desktop.
Save giann/6a1cc45e36dd10afae30744f9b8193ac to your computer and use it in GitHub Desktop.
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