gpt4 book ai didi

async-await - 在 babel 6 和 webpack 中使用 async/await 的正确方法

转载 作者:行者123 更新时间:2023-12-02 21:52:31 25 4
gpt4 key购买 nike

我只是想探索 async/await 。当我调用该函数时,我在控制台中得到了这个:

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

最佳答案

return wait 的结果将是一个 promise ,正如控制台日志告诉您的那样。要访问解析的值,您需要使用 then 链接调用,或者需要位于另一个可以使用 wait 解析的异步函数内。

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()

关于async-await - 在 babel 6 和 webpack 中使用 async/await 的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38460784/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com