当对babel和ES6 promise使用async await时,无法解析promise
Unable to resolve promise when using async await with babel and ES6 promise
我有以下节点应用程序包含一个async函数,等待ES6的承诺。
async function test(id){
try {
let val = await Promise.resolve(id);
console.log("val: " + val);
} catch (error) {
console.log("error: " + error);
}
}
test(1);
Result = val: undefined
预期结果:val: 1
我使用gulp-babel将其编译为ES5。
我在gulp任务中设置了以下内容:
.pipe(babel({ optional: ["es7.asyncFunctions"] }))
我也要求在'babel/polyfill'后npm安装babel。
Transpiled代码:
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);
您似乎正在使用Babel版本5.5.0
之前的Babel版本。在此版本之前,可以将regenerator
(Babel的依赖项)安装在低于0.8.28
的版本上,这是regenerator
开始支持await Promise.resolve(value)
(示例中的代码)的第一个版本。
支持在regenerator
端被添加,Babel升级到至少需要0.8.28
版本的regenerator。
我认为你必须等待测试函数。因为测试函数等待一个承诺,所以当你在其他上下文中调用它时,等待测试函数将帮助你等待,直到它完成。
相关文章:
- 使用promise和mongoose对文档进行排序
- 测试Angular Service解决错误回调中的promise
- 节点协同与生成器和Promise并行流量控制
- 根据是否解析了 Promise 从函数返回值
- jQuery加载的async和ready函数不工作
- 将一个方法转换为promise:Nodejs
- 函数在promise被解析后被调用,但Jasmine未通过测试.为什么?
- async问题,JS Promise无法返回结果,但可以使用console.log
- 如何将嵌套_.each转换为同步方法?首选使用 Promise 或 Async.waterfall
- 如何在 Node JS FS 模块中使用 Typescript Async/ await with promise
- Typescript async/await Promise调用差异
- 使用.join()在async promise内部调用async promises
- 在Promise中包装async循环
- undefined with promise async / await
- 为什么bluebird promise内部的async函数抛出的错误没有被.catch()函数捕获?
- 如何从async.js中使用Promise进行编码
- 带有promise/async-await的回调上下文
- 如何替换'Async=false'javascript中的promise
- ES2017 Async/await函数-它们只与promise一起工作吗
- 当对babel和ES6 promise使用async await时,无法解析promise