正确使用async / await与babel 6和webpack的方法

时间:2016-07-19 14:02:58

标签: async-await webpack babeljs ecmascript-next

我只是想探索异步/等待。当我调用该函数时,我在控制台中得到了它:

Promise { <state>: "pending" }

这是我的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()]
};

和我的职能:

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

和被调用的方法:

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

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

1 个答案:

答案 0 :(得分:8)

return await的结果将是一个承诺,就像您的控制台日志告诉您一样。要访问已解析的值,您需要使用then链接您的调用,或者您需要位于另一个可以使用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()