Async Iterators and more in TS 2.3

ref: https://blogs.msdn.microsoft.com/typescript/2017/04/10/announcing-typescript-2-3-rc/

TypeScript 2.3 brings support for async generators and async iterators. You can read more about these features on the TC39 proposal, but we’ll try to give a brief explanation and example.

Async iterators are an upcoming ECMAScript feature that allows iterators to produce results asynchronously. They can be cleanly consumed from asynchronous functions with a new construct called async for loops. These have the syntax

for await (let item of items) {
    /*...*/
}

Async generators are generators which can await at any point. They’re declared using a syntax like

async function* asyncGenName() {
    /*...*/
}

Let’s take a quick look at an example that use both of these constructs together.

// Returns a Promise that resolves after a certain amount of time.
function sleep(milliseconds: number) {
    return new Promise<void>(resolve => {
        setTimeout(resolve, milliseconds);
    });
}

// This converts the iterable into an async iterable.
// Each element is yielded back with a delay.
async function* getItemsReallySlowly<T>(items: Iterable<T>) {
    for (const item of items) {
        await sleep(500);
        yield item;
    }
}

async function speakLikeSloth(items: string[]) {
    // Awaits before each iteration until a result is ready.
    for await (const item of getItemsReallySlowly(items)) {
        console.log(item);
    }
}

speakLikeSloth("never gonna give you up never gonna let you down".split(" "))

Keep in mind that our support for async iterators relies on support for Symbol.asyncIterator to exist at runtime. You may need to polyfill Symbol.asyncIterator, which for simple purposes can be as simple as

(Symbol as any).asyncIterator = Symbol.asyncIterator || Symbol.from("Symbol.asyncIterator");

or even

(Symbol as any).asyncIterator = Symbol.asyncIterator || "__@@asyncIterator__";

If you’re using ES5 and earlier, you’ll also need to use the --downlevelIteration flag. Finally, your TypeScript lib option will need to include "esnext".

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s