2016-07-19 39 views
2

我只是想探索異步/等待。當我調用函數我在控制檯得到這個:正確的方式來使用異步/等待與babel 6和webpack

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()); 
    } 
..... 

回答

8

的結果將是一個承諾,就像你的控制檯日誌告訴你的一樣。要訪問解析的值,您需要將您的呼叫鏈接到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()