简体   繁体   中英

Babel transpiles async but not await?

Babel transpiles everything correctly exept await in the following snippet and configuration using webpack:

async function myMethod(i) {
    let j = i * i;
    return j;
}

let x = myMethod(2);

console.log(myMethod)
console.log(x);

let y = await myMethod(2);

The results are:

console.log(myMethod) // returns a function.
console.log(x) // returns a promise

Now the weird thing is, that with the last line I get an "Unexpected token" error form babel. How can that be?

Package.json:

"devDependencies": {
  "babel": "^6.5.2",
  "babel-loader": "^6.2.4",
  "babel-polyfill": "^6.7.4",
  "babel-preset-es2015": "^6.6.0",
  "babel-preset-react": "^6.5.0",
  "babel-preset-stage-0": "^6.5.0",
  "react": "^0.14.8"
}

Webpack.config:

var path = require('path');
var webpack = require('webpack');

module.exports = {
    context: path.join(__dirname),
    entry: ['babel-polyfill', './App/main.js'],

    [..]

    module: {
        loaders: [
          {
              test: /\.jsx?$/,
              exclude: /node_modules/,
              loader: 'babel',
              query: {
                  presets: ['es2015', 'stage-0', 'react'],
              },
          },
        ],
    },

    [..]

    resolve: {
        extensions: ['', '.js', '.jsx'],
    }
}

To my best knowledge, to use await it has to be wrapped in an async function.

So you can change:

let y = await myMethod(2);

to be:

async function main() {
  let y = await myMethod(2);
}

main();

and it should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM