在使用Node.js中的await/async时出现意外的标识符。

4

当我在Node.js中使用async或await时,出现了意外的标识符错误。我使用的是Node版本8.5.0。这完全阻碍了我的进展。有没有什么方法可以解决这个问题?

async function methodA(options) {
    rp(options)
        .then(function (body) {            
            serviceClusterData = JSON.parse(body);         
            console.log("Step 2");
            console.log("Getting cluster details from zookeeper");
        })
        .catch(function (err) {
            console.log("Get failed!");

        });
}

await methodA(options);
console.log("Step 3!");

尝试了第一个答案后,我做了如下操作:
var serviceClusterData = "";
            console.log("Step 1!");

            ////////////////////

            async function methodA(options) {
                await rp(options)
                    .then(function (body) {
                        serviceClusterData = JSON.parse(body);
                        console.log("Step 2");
                        console.log("Getting cluster details from zookeeper");
                    })
                    .catch(function (err) {
                        console.log("Get failed!");

                    });
            }

            methodA(options);
            console.log("whoops Step 3!");

仍然出现顺序问题 :( 步骤1 步骤3 步骤2


有办法的:请展示你的代码。 - TGrif
已更新问题并附上代码。谢谢。 - user461112
可能是'await Unexpected identifier' on Node.js 7.5的重复问题。 - Michał Perłakowski
2个回答

5

在异步函数之外,您无法使用 await

async function methodA(options) {
    await rp(options)
        .then(function (body) {            
            serviceClusterData = JSON.parse(body);         
            console.log("Step 2");
            console.log("Getting cluster details from zookeeper");
        })
        .catch(function (err) {
            console.log("Get failed!");

        });
}

methodA(options);
console.log("Step 3!");

是的,这就是预期的结果顺序。 - TGrif
有没有办法在A方法完成之前阻止执行console.log("whoops Step 3!"); - user461112
1
@user461112,一个async函数返回一个Promise,所以你可以像处理Promise一样处理它:methodA(options).then(() => console.log('Step 3!')) - robertklep
@user461112 可以选择并行执行 Promise.all([ methodA(), methodB() ]).then(...) 或者串行执行 methodA().then(() => methodB()).then(...)。或者创建一个新的异步函数,使用 await 调用两个方法,然后以类似的方式调用 函数。 - robertklep
@robertklep:我想按顺序运行它...但看起来它不适用于.then。让我更新问题以展示我的代码。 - user461112
显示剩余2条评论

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接