有一个异步函数(send
),如果未定义msg
属性,则另一个函数(getNextProcess
)会设置其值。
getNextProcess
在Promise中执行数据库查询。查询回调Promise resolve函数。
问题:
使用Babel翻译代码后,msg
将始终为'undefined'。
Promise在后台独立运行,并以正确的值返回(已通过控制台日志检查)。
/* ORIGINAL */
class MyClass(){
/*
construct & other codes here...
*/
getNextProcess(){
new Promise(res => {
logDb.get("SELECT * FROM process WHERE details NOT LIKE '%isComplete:true%' ORDER BY id LIMIT 1", (e, r) => {
let result = JSON.parse(r.details);
result.id = r.id;
res(result);
});
});
}
async send(msg = undefined){
if (!msg) msg = await this.getNextProcess();
webView.send('webview:receive', msg);
}
}
/* Transformed */
{
key: "send",
value: function () {
var _send = (0, _asyncToGenerator2["default"])(
/*#__PURE__*/
_regenerator["default"].mark(function _callee() {
var msg,
_args = arguments;
return _regenerator["default"].wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
msg = _args.length > 0 && _args[0] !== undefined ? _args[0] : undefined;
if (msg) {
_context.next = 5;
break;
}
_context.next = 4;
return this.getNextProcess();
case 4:
msg = _context.sent;
case 5:
this.webView.send('webview:receive', msg);
case 6:
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
function send() {
return _send.apply(this, arguments);
}
return send;
}()
}
/* package.json */
// ...
"scripts": {
"start": "npm run compile && electron main.js",
"compile": "browserify -t [ babelify --presets [ @babel/preset-env ] ] src/app.js -o js/app.js",
},
"devDependencies": {
"@babel/core": "^7.4.5",
"@babel/plugin-transform-async-to-generator": "^7.4.4",
"@babel/plugin-transform-regenerator": "^7.4.5",
"@babel/plugin-transform-runtime": "^7.4.4",
"@babel/preset-env": "^7.4.5",
"@babel/runtime": "^7.4.5",
"babel-core": "^7.0.0-bridge.0",
"babelify": "^10.0.0",
"browserify": "^13.0.1",
"electron": "^4.1.4",
"electron-rebuild": "^1.8.5"
},
// ...
/* .babelrc */
{
"presets": [
[
"@babel/preset-env",
{
"useBuiltIns": "entry"
}
]
],
"ignore": [
"../node_modules/jquery/dist/jquery.js"
],
"plugins": [
["@babel/plugin-transform-runtime", {
"helpers": true,
"regenerator": true
}],
"@babel/plugin-transform-async-to-generator",
"@babel/plugin-transform-regenerator",
]
}
答案 0 :(得分:2)
您似乎忘记了在getNextProcess中返回诺言。
await
不知道如果不答应等待什么。
getNextProcess(){
return new Promise(res => {
//...
});
}