繁体   English   中英

在Node.js中使用等待/异步时出现意外标识符

[英]unexpected identifier when using await/async in nodejs

当我在nodejs中使用async或await时,我得到了意外的标识符。 我正在使用节点版本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

您不能在异步函数之外使用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!");
'use strict'

function methodA(options) {

    return new Promise(resolve => {
        setTimeout(() => {
            console.log(1)
            resolve(true);
        }, 2000);
    })
}

//Sync Declartion
async function test() {
    //Await declaration
    await methodA({});
    console.log(2);
}
test();

您的代码似乎存在语法错误。 上面的代码在8.5.0中有效

参考https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/async_function

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM