【发布时间】:2015-08-21 14:37:07
【问题描述】:
我有以下包含异步函数的节点应用程序,正在等待 ES6 承诺。
async function test(id){
try {
let val = await Promise.resolve(id);
console.log("val: " + val);
} catch (error) {
console.log("error: " + error);
}
}
test(1);
结果 = val: 未定义
预期结果:val:1
我使用 gulp-babel 将其编译为 ES5。
我在 gulp 任务中有以下设置:
.pipe(babel({ optional: ["es7.asyncFunctions"] }))
在 npm 安装 babel 之后,我还需要在 'babel/polyfill' 中。
转译代码:
function test(id) {
var val;
return regeneratorRuntime.async(function test$(context$1$0) {
while (1) switch (context$1$0.prev = context$1$0.next) {
case 0:
context$1$0.prev = 0;
context$1$0.next = 3;
return Promise.resolve(id);
case 3:
val = context$1$0.sent;
console.log('val: ' + val);
context$1$0.next = 10;
break;
case 7:
context$1$0.prev = 7;
context$1$0.t0 = context$1$0['catch'](0);
console.log('error: ' + context$1$0.t0);
case 10:
case 'end':
return context$1$0.stop();
}
}, null, this, [[0, 7]]);
}
test(1);
【问题讨论】:
-
能否展示一下转译后的代码?
-
嗯,看起来应该可以了。奇数。
-
根据我的经验,将 try catch 语句与 promise 一起使用并不是一个好习惯。这就是为什么你有像 Promise.fail() 这样的 API 调用。但我不熟悉 Babel 如何处理 Promise,所以我可能是错的。
-
@tutiplain async/await 的优点之一是您应该能够使用 try/catch 。
-
你使用的是最新版本的 Babel 吗?当我使用
babel-node运行它时,我得到val: 1。
标签: javascript node.js async-await babeljs es6-promise