Last active
April 21, 2021 19:05
-
-
Save korzio/52774b2cf2281662ca0e6ef4600bf6bd to your computer and use it in GitHub Desktop.
Based on impressions of Kyle Simpson's "JavaScript: The Recent Parts" workshop - https://frontendmasters.com/courses/js-recent-parts/ . The task is to demonstrate the ability of iterating async requests with asap strategy, where both all the requests are done, and the results are returned as soon as possible
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
async function get(n) { | |
return new Promise(r => setTimeout(() => r(n), n * 100)) | |
} | |
async function* asyncGenerator(arr) { | |
let anyResolve | |
arr.map(get).forEach(async request => { | |
const anyResult = await request | |
anyResolve(anyResult) | |
}) | |
while(true) { | |
yield await new Promise((resolve) => { | |
anyResolve = resolve | |
}) | |
} | |
} | |
(async function() { | |
for await (let num of asyncGenerator([4, 3, 2, 1, 0])) { | |
console.log(num) | |
} | |
})() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What if
asyncGenerator
was something like this? I think it would achieve resolution in order of requests (4, 3, 2, 1, 0) no matter what "network" delay each step gets.UPD. Although, it's not what we want, since it doesn't fire next request until previous is resolved.
@korzio, btw, check your code with
get
function withrandomDelay
from my example above.