Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Based on impressions of Kyle Simpson's "JavaScript: The Recent Parts" workshop - . 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 request => {
const anyResult = await request
while(true) {
yield await new Promise((resolve) => {
anyResolve = resolve
(async function() {
for await (let num of asyncGenerator([4, 3, 2, 1, 0])) {

This comment has been minimized.

Copy link
Owner Author

korzio commented Jun 19, 2019

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

This comment has been minimized.

Copy link

koshilki commented Jun 19, 2019

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


This comment has been minimized.

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
You can’t perform that action at this time.