我有以下节点应用程序包含一个异步功能,等待一个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。
我在吞咽任务中设置了以下内容:
.pipe(babel({ optional: ["es7.asyncFunctions"] }))我还要求在' babel /polyfill‘后npm安装babel。
转换后的代码:
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);发布于 2015-08-03 22:08:41
发布于 2021-08-15 04:45:59
我认为你必须等待测试函数。因为测试函数等待一个承诺,所以当你在其他上下文中调用它时,等待测试函数将帮助你等待,直到它完成。
https://stackoverflow.com/questions/30686945
复制相似问题