-
-
Save forkfork/4833ab6f9be5f0a2ca9510d551e9d0b9 to your computer and use it in GitHub Desktop.
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
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