for await (... of ...) not working. Babel present env, node v10

1.5k Views Asked by At

It's been a while since I started a nodejs project from scratch, so was a bit of a headscratcher to set up and configure eslint, babel etc.

right now my babelrc is :

{
  "presets": [
    [
      "env",
      {
        "targets": {
          "node": "10"
        }
      }
    ]
  ],
  "plugins": [
    [
      "transform-runtime",
      {
        "regenerator": true
      }
    ]
  ]
}

package.json has dev dependencies:

"babel-cli": "^6.26.0",
"babel-plugin-transform-runtime": "^6.23.0",
"babel-preset-env": "^1.7.0",

Now I want to loop over a list of objects. For each, I need to perform some asynchronous tasks that I'll need to await on, so I did:

for await (const thing of things) {
  const foo = await doSomethingThatTakesAwhile(thing)
  // etc
}

but when I run it in dev (nodemon via babel-node) now there's a syntax error on the await:

for await (const thing of things) {
    ^
Syntax Error Unexpected token, expected (
    at Parser.pp$5.raise (... \node_modules\babylon\lib\index.js:4454:13)
    at Parser.pp.unexpected (... \node_modules\babylon\lib\index.js:1761:8)
    at Parser.pp.expect (... \node_modules\babylon\lib\index.js:1749:33)
    at Parser.pp$1.parseForStatement (... \node_modules\babylon\lib\index.js:2008:8)
etc..

Do I have to change my babel config, and/or have I completely misunderstood for/await and await/async ?

2

There are 2 best solutions below

0
On BEST ANSWER

I found another project in which i know for await of works... it looks like I'm using old babel plugins and not the new, separated out @babel/xxx libs. After trial and error installing and uninstalling stuff: this is the resulting babelrc that worked:

{
  "presets": [
    [
      "@babel/preset-env",
      {
        "targets": {
          "node": "10"
        }
      }
    ]
  ],
  "plugins": [
    [
      "@babel/plugin-transform-runtime",
      {
        "regenerator": true
      },
      "@babel/preset-env"
    ]
  ]
}

By this point I had installed all of:

  • @babel/core
  • @babel/node
  • @babel/cli
  • @babel/preset-env
  • @babel/plugin-transform-runtime

Then I ran into this issue: https://github.com/meteor/meteor/issues/10128 So Had to also install @babel/runtime pegged at 7.0.0-beta.55 ... and now it builds!!

2
On

I believe you need the babel-plugin-proposal-async-generator-functions plugin to use the for await of syntax.