我有一个包含异步函数的节点应用程序,等待ES6 promise。
async function test(id){
try {
let val = await Promise.resolve(id);
console.log("val: " + val);
} catch (error) {
console.log("error: " + error);
}
}
test(1);
结果 = val: undefined
期望的结果: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);
Promise.resolve()
调用的结果。例如,如果你从使用 Promises 的某个库中获取了一个 Promise 的引用,比如var promise = myLibrary.asyncMethod()
,然后执行let val = await promise
,它应该可以工作。 - Matt Brownebabel-node
运行它时,会得到val: 1
。 - Matt Browne