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) | |
} | |
})() |
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.
// async function get(n) {
// let randomDelay = (Math.round(Math.random() * 1E4) % 8000) + 1000 // randomDelay from original Kyle example
// return new Promise(r => setTimeout(() => r(n), randomDelay))
// }
async function * asyncGenerator(arr) {
let index = 0
while (index < arr.length) {
yield get(arr[index])
index += 1
}
}
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 with randomDelay
from my example above.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
IIRC, the problem we were trying to solve was to yield values in order of promise resolution, right?
It does make sense, though, there's might be something of race condition there - imagine two
get
promises resolving "simultaneously" (i.e. one gets resolved before the previous value is yielded). You don't have a anotherresolve
available in this case.So yes, it'll work in some cases, but I wouldn't like to see something like this in production code ;)