javascript - 访问承诺内设置的类属性
问题描述
来自 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)
我正在尝试访问isBound
promise return 之外的属性,在成功的身份验证方法中它被设置为 true。
但是,正如您所见,似乎存在可能的竞争条件?
有没有办法处理这个...
谢谢
解决方案
这不是竞争条件。它按预期工作正常。您的代码中有两个console.logs
。第一个在承诺中,另一个在承诺之外。
您的调用进入异步模式,最后console.log
一个命令按顺序作为下一个命令执行,当时变量的值为null
. 您的变量稍后会使用正确的值解析。
如果您必须执行进一步的操作,您必须在.then()
您的方法部分执行此操作,该部分仅在您解决后Client
才会执行。Promise
例如
Client().then() {//all of your post response related logic should be here}
推荐阅读
- c# - C#从httplistener发送图片
- java - 运行时未添加 NetBeans Gradle 影子依赖项
- javascript - 即使输入不为空也无法提交表单
- python - 如何在标题旁边列出价格数据?例如:Pepsi Pepsi Max - 330 毫升 LBP 17,999
- python - pycharm django 安装 mysqlclient 失败
- sql-server - 使用别名从一列中为所有行填写数据
- java - 顶点中的文本未居中
- pdf - 如何在 Edge 中打开 pdf,例如在 Internet-Explorer 中使用命令行中的 args 搜索标签?
- python - ColumnTransformer 在管道中使用 CountVectorizer/HashingVectorizer 失败(多个文本特征)
- asp.net - 搜索功能无法按姓名和姓氏查找用户