tc39/proposal-async-iteration

implicit await in `yield` and `return`

awto opened this issue · 1 comments

awto commented

Looking at the specification for arguments of yield and return implementation needs to add another await.

Regenerator does this, babel doesn't do this and returns promise if it is indeed promise passed to yield/return, but it doesn't sound right according to the spec.

What are the reasons behind this in the spec? It looks like an obstacle for me. What if I want to return a set of Promises to run it after in, say, Promise.all?

Also may be confusing, as everywhere the async position in expressions marked explicitly and only in these two places it is implicit.

This has been discussed in the past and was changed to be equivalent to yield await due to complex cases.

If you're asking how with yield acting as yield await can you run things concurrently? Well it's basically the same way as before:

// This presumes you want the downloads to be yield-ed in the same
// order as `urls`, the unordered one is similar but
// races the `active` array instead of waiting for the first
async function* concurrentDownload(urls, maxConcurrency=10) {
    const active = []
    for (const url of urls) {
        // Add download to list of concurrently active
        active.push(downloadOne(url))
        // But if we've hit max concurrency we'll wait for the first
        // one to complete before we continue
        if (active.length === maxConcurrency) {
            yield active.shift()
        }
    }
    // Yield the ones left in the queue
    for (const download of active) {
        yield download
    }
}