Skip to content

Instantly share code, notes, and snippets.

@korzio
Last active April 21, 2021 19:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save korzio/52774b2cf2281662ca0e6ef4600bf6bd to your computer and use it in GitHub Desktop.
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
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
Copy link
Author

korzio commented Jun 19, 2019

  1. Is it what Kyle was showing?
  2. Does it make sense?

@koshilki
Copy link

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 ;)

@dfsq
Copy link

dfsq commented Jul 1, 2019

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