首页 > 解决方案 > 访问承诺内设置的类属性

问题描述

来自 PHP 的深厚背景,我在 node/js 的某些方面苦苦挣扎。

const ldap = require('ldapjs');

class LdapClient {
  constructor({
    url,
  }) {
    this.isBound = null;
    this.client = ldap.createClient({ url });
  }

  authenticate(credentials) {
    const _this = this;

    return new Promise((resolve, reject) => {
      return this.client.bind(credentials.username, credentials.password, (err, res) => {
        if (err) {
          this.client.unbind();
          return reject(err);
        }

        _this.isBound = true;

        return resolve(res);
      });
    });
  }
}
const client = new Client({url: ''})

const credentials = {
  'username': '',
  'password': ''
}

client.authenticate(credentials)
  .then(() => {
    console.log('authenticated');
    console.log('race = ' + client.isBound); // SHOWS TRUE
  })
  .catch(e => {
    console.log(e);
  })

console.log(client.isBound); // SHOWS NULL... WANT TRUE (RACE ISSUE as consoles before PROMISE)

我正在尝试访问isBoundpromise return 之外的属性,在成功的身份验证方法中它被设置为 true。

但是,正如您所见,似乎存在可能的竞争条件?

有没有办法处理这个...

谢谢

标签: javascriptnode.jsecmascript-6

解决方案


这不是竞争条件。它按预期工作正常。您的代码中有两个console.logs。第一个在承诺中,另一个在承诺之外。

您的调用进入异步模式,最后console.log一个命令按顺序作为下一个命令执行,当时变量的值为null. 您的变量稍后会使用正确的值解析。

如果您必须执行进一步的操作,您必须在.then()您的方法部分执行此操作,该部分仅在您解决后Client才会执行。Promise

例如

Client().then() {//all of your post response related logic should be here}

推荐阅读