当对babel和ES6 promise使用async await时,无法解析promise

Unable to resolve promise when using async await with babel and ES6 promise

本文关键字:promise async babel ES6 使用 当对 await      更新时间:2023-09-26

我有以下节点应用程序包含一个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。

我认为你必须等待测试函数。因为测试函数等待一个承诺,所以当你在其他上下文中调用它时,等待测试函数将帮助你等待,直到它完成。