Skip to content

Async generator function does not flatten yielded promises #15205

Closed

Description

TS 2.3 RC

declare const console: any;
{
    (Symbol as any).asyncIterator = Symbol.asyncIterator || "__@@asyncIterator__";

    const gen = async function* () {
        yield Promise.resolve(10)
        yield Promise.resolve(20)
    }

    const main = async () => {
        for await (const y of gen()) {
            console.log(y)
        }
    }

    main();
}

This outputs:

❯ tsc && node ./target/AsyncIterable.js
Promise { 10 }
Promise { 20 }

I expected it to output (promises are flattened):

10
20

Activity

  1. masaeedu commented on Apr 16, 2017

    @masaeedu
    Contributor

    Oliver Joseph Ash (@OliverJAsh) Not super familiar with this, but I think you might want to be yield await-ing stuff inside gen. Does this work?

    declare const console: any;
    {
        (Symbol as any).asyncIterator = Symbol.asyncIterator || "__@@asyncIterator__";
    
        const gen = async function* () {
            yield await Promise.resolve(10)
            yield await Promise.resolve(20)
        }
    
        const main = async () => {
            for await (const y of gen()) {
                console.log(y)
            }
        }
    
        main();
    }

    I think the point of marking a function with async is so that you can write your code inside as if it was synchronous, await-ing at any points where you have to interact with asynchronous code. The transpiler machinery wraps all this appropriately so that your function obeys the async-iterator interface and returns promises from next.

  2. OliverJAsh commented on Apr 17, 2017

    @OliverJAsh
    ContributorAuthor

    Ah, interesting.

    I can confirm this does fix the issue, although I have a feeling the flattening should work without the await. I don't know if it's anything to go by, but this works in Babel.

  3. masaeedu commented on Apr 17, 2017

    @masaeedu
    Contributor

    Oliver Joseph Ash (@OliverJAsh) I did some digging and it looks like there was an issue filed in the proposal repo to make it behave as you are describing: tc39/proposal-async-iteration#8. This means TypeScript isn't following the spec, and should be unwrapping as you expected.

  4. locked and limited conversation to collaborators on Jun 14, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

BugA bug in TypeScriptFixedA PR has been merged for this issue

Type

No type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions