【问题标题】:ES6 node async/await unexpected identifierES6 节点异步/等待意外标识符
【发布时间】:2017-06-19 00:17:11
【问题描述】:

我有以下代码在运行 babel 时有效。现在我正在使用 Harmony,我收到以下错误:

let adResult = await ad.isUserValid(domainPath, password);
^^
SyntaxError: Unexpected identifier

如下类函数:

class ActiveDirectoryHelper {
    constructor(options) {
        this.config = options.config
        this.ad = null;
    }

    connect() {

        var config = {
            url: this.config.url,
            baseDN: this.config.baseDN,
            attributes: this.config.attributes
        };

        if (this.config.account.user.length > 0) {
            config.username = this.config.account.user;
            config.password = this.config.account.password;
        }

        this.ad = new ActiveDirectory(config);
    }

    async isUserValid(user, password) {
        return new Promise((resolve, reject) => {

            this.ad.authenticate(user, password, (err, auth) => {
                if (err) {
                    reject({
                        code: 500,
                        message: "Unknown authentication error",
                        entry: {}
                    });
                }

                if (auth) {
                    resolve({
                        code: 200,
                        message: "OK",
                        entry: {
                            user: user,
                            password: password
                        }
                    });

                } else {
                    reject({
                        code: 400,
                        message: "Authentication failed",
                        entry: {}
                    });

                }

            });
        });
    }
...

exports.ActiveDirectoryHelper = ActiveDirectoryHelper;

我使用的类如下:

const ad = new ActiveDirectoryHelper({
    config: adConfig
});
ad.connect();

const domainPath = domain.length > 0 ? `${domain}\\${user}` : user;
const adResult = await ad.isUserValid(domainPath, password);

我使用以下参数运行代码:

node --harmony --use_strict --harmony-async-await user.js <my parameters>

如果我在调用方法时采取await:

const adResult = ad.isUserValid(domainPath, password);

然后我没有错误,但它也不会等到方法完成。 我已经用谷歌搜索了这个错误,看起来你只能在 async 所在的函数中使用 await 。但是如果在方法调用之外没有 await ,它不会等到它完成。有什么想法吗?

【问题讨论】:

  • 您使用的是哪个版本的node
  • 听起来您使用的是旧版本的 Node.js。从 Node 4.3 开始的任何版本都应该支持 let 关键字。
  • 你们是对的,我切换了我认为具有最新版本 7 的计算机。一旦我更新它就可以了。感谢您的提示

标签: javascript async-await es6-promise


【解决方案1】:

这是因为您不能使用 await,除非它在 ​​async 函数中。

查看此链接了解详情:

'await Unexpected identifier' on Node.js 7.5

【讨论】:

  • 在异步函数中遇到此错误,无法解决。我在array.forEach(item =&gt; { x = await ... }) 调用中有一个等待,当然这是一个函数,所以我只需要让它异步:array.forEach(async item =&gt; { x = await ... })
猜你喜欢
  • 2018-01-17
  • 1970-01-01
  • 2018-04-08
  • 1970-01-01
  • 1970-01-01
  • 2017-07-02
  • 2018-08-17
  • 1970-01-01
相关资源
最近更新 更多