Search code examples
async-awaitwebpackbabeljsecmascript-next

correct way to use async/await with babel 6 and webpack


I am just trying to explore async/await . When I call the function I got this in my console:

Promise { <state>: "pending" }

Here is my webpack.conf.js:

var path = require("path");
var webpack = require('webpack');
var BundleTracker = require('webpack-bundle-tracker');

module.exports = {
    devtool: 'eval',
    entry: [
         'babel-regenerator-runtime',
        './static/apps/app.jsx'
    ],
    output : {
        path: __dirname,
        filename: "./static/js/bundles/[name]-[hash].js"
    },
    module: {
        loaders: [
            {
                test: /\.jsx?$/,
                loader: 'babel-loader',
                exclude: /node_modules/,
                query: {
                    plugins: [ 'transform-decorators-legacy', 'syntax-async-functions', 'transform-async-to-generator'],
                    presets: ['react', 'es2015', 'stage-0']
                }
            }
        ]
    },
    plugins: process.env.NODE_ENV === 'production' ? [
        new webpack.optimize.DedupePlugin(),
        new webpack.optimize.OccurrenceOrderPlugin(),
        new webpack.NoErrorsPlugin(),
        new webpack.optimize.UglifyJsPlugin({
        compress: { warnings: false },
            comments: false,
            sourceMap: true,
            mangle: true,
            minimize: true
    })
    ] : [new BundleTracker({filename: './webpack-stats.json'}), new webpack.NoErrorsPlugin()]
};

and my function:

export async function x() {
    return await (5 * 5);
}

and the called method:

import {x} from '../utils/pgp.js';

.....
componentWillMount(){
        console.log(x());
    }
.....

Solution

  • The result of return await will be a promise, just as your console log is telling you. To access the resolved value, you need to chain your call with then, or you need to be inside another async function which can resolve using await.

    async function x () {
      return await 5 * 5
    }
    
    // using `.then`
    x().then(value => console.log(value))
    
    // inside another async function
    async function main () {
      let value = await x()
      console.log(value)
    }
    
    main()