【问题标题】:unexpected identifier when using await/async in nodejs在 nodejs 中使用 await/async 时出现意外标识符
【发布时间】:2018-03-01 07:26:11
【问题描述】:

当我在 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步 第三步 第二步

【问题讨论】:

标签: javascript promise async-await


【解决方案1】:
'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/en-US/docs/Web/JavaScript/Reference/Statements/async_function

【讨论】:

    【解决方案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!");
    

    【讨论】:

    • 嗨,我现在尝试了这个并更新了问题。我仍然无法正常使用 console.log 语句。 :(@TGrif
    • 是的,这是预期的结果顺序。
    • 有没有办法阻止 console.log("whoops Step 3!"); 的执行,直到方法 A 完成?
    • @user461112 一个async 函数返回一个promise,所以你可以把它当作一个:methodA(options).then(() => console.log('Step 3!'))
    • @robertklep 谢谢!这样可行。当你有两种方法时它会如何工作 - 类似的 methodA 和 methodB(都使用 async 和 await)
    猜你喜欢
    • 2017-09-03
    • 2023-04-01
    • 1970-01-01
    • 2019-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-08
    相关资源
    最近更新 更多