Async Generator works on babel-node but fails w/ babel-register or build

396 Views Asked by At

Using babel-node I was able to run the following code

function timeout(ms = 100) {
  return new Promise(resolve => {
    let id = setTimeout(() => {
                        clearTimeout(id)
    resolve(ms)
  }, ms)
})
}

async function* worker(limit = 10) {
  async function fetch() {
    return await timeout(Math.random() * 1000)
  }

  let low = 0;
  while (low++ < limit) yield await fetch()
}

async function run() {
  const gen = worker(5)
  const results = [];
  for await (const res of gen) {
    console.log('working')
    results.push(res)
  }

  return 'done'
}

run().then(res => console.log(res)).catch(err => console.error(err))

Doesn't work here, but works on the online Babel REPL

As well as when I run it through babel-node like:

babel-node src/script.js

It however fails when I build and run it like so:

babel src/script.js --out-file dist/script.js
node dist/script.js

and gives me

TypeError: iterable[Symbol.iterator] is not a function

Using babel-register also fails w/ the same error:

node -r babel-register -r dotenv/config src/script.js

My current .babelrc looks like

{
    "plugins": ["transform-strict-mode", "transform-async-generator-functions"],
    "presets": ["es2015-node6", "stage-2"]
}

using es2015 instead of es2015-node6 yielded no benefit

When I looked at the default plugins and presets used for babel-node here , and looks like they're empty

What am I missing?

1

There are 1 best solutions below

2
On BEST ANSWER

babel-node (and the online REPL), in addition to handling runtime transpiling, also requires babel-polyfill. You should npm i -S babel-polyfill and then import 'babel-polyfill'; at your program's entrypoint (or in your example, add -r babel-polyfill to your node args).