Skip to content

Instantly share code, notes, and snippets.

@nikolaybotev
Created September 16, 2024 12:03
Show Gist options
  • Save nikolaybotev/acab33b7387e4773bc1749f1c556efbb to your computer and use it in GitHub Desktop.
Save nikolaybotev/acab33b7387e4773bc1749f1c556efbb to your computer and use it in GitHub Desktop.
Setup AsyncIteratorPrototype for Common.js Async Iterator Helpers polyfill on async generators
const asyncGeneratorInstancePrototype = Object.getPrototypeOf(async function*(){}());
const AsyncGeneratorPrototype = Object.getPrototypeOf(asyncGeneratorInstancePrototype);
let AsyncIteratorPrototype;
if (AsyncGeneratorPrototype === Object.prototype) {
// Fix-up for babel's transform-async-generator-functions
AsyncIteratorPrototype = {};
const newAsyncGeneratorPrototype = Object.create(AsyncIteratorPrototype);
Object.setPrototypeOf(asyncGeneratorInstancePrototype, newAsyncGeneratorPrototype);
} else {
AsyncIteratorPrototype = Object.getPrototypeOf(AsyncGeneratorPrototype);
}
import configurator from "core-js/configurator.js";
configurator({ AsyncIteratorPrototype });
@nikolaybotev
Copy link
Author

Add this file to your project and import it at the top of your entry-point, to enable Async Iterator Helper polyfills from core-js on async generator functions, e.g.:

// Add this at the top of your entry point script only and before require'ing core-js async-iterator-helpers:
import "./async-iterator-setup.mjs";

import "core-js/proposals/async-iterator-helpers";

async function* gen() {
  yield* [1, 2, 3, 4, 5];
}

gen()
  .drop(1) // Using Async Iterator Helpers here works
  .take(3)
  .filter(n => n != 3)
  .map(n => n * 10)
  .forEach(n => console.log(n));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment