-
-
Save korzio/52774b2cf2281662ca0e6ef4600bf6bd to your computer and use it in GitHub Desktop.
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) | |
} | |
})() |
korzio
commented
Jun 19, 2019
- Is it what Kyle was showing?
- Does it make sense?
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 another resolve
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 ;)
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.