【发布时间】:2020-05-11 01:51:25
【问题描述】:
在 submitButton 事件中,我想检查是否有用户注册。
假设有 5 个用户注册:
getUsers = function () {
return new Promise(function (resolve, reject) {
resolve(5);
reject(0);
});
}
在 checkregisteredUsers 中,我调用 getUsers,然后检查是否有任何用户。如果有任何用户,则返回 true,否则返回 false。我设置了 UsersFound 的状态。
checkRegisteredUsers = () => {
return this.getUsers().then(result => {
return this.setState({ UsersFound: result > 0 ? true : false };
}).catch(reason => {
console.log(reason);
});
}
现在,在函数 submitButton 中,我想检查是否有注册用户。
submitButton = () => {
this.checkRegisteredUsers().then(result => {
this.setState({ UsersFound: result > 0 ? true : false });
});
if(!this.state.UsersFound){
return; **//exit code here and the rest of the code below should not execute and show the dialog box**
}
// run some other code
}
当我调用 submitButton 时,尚未设置 UsersFound 的状态。如果我再次单击它,则它已设置。 我怎样才能将它设置在一个承诺中?或者如何使用 Promise 在 submitButton 中检查真/假?
编辑:
问题是:我如何从 Promise 中返回布尔值,因为我想检查如下内容:
submitButton = () => {
if(this.checkRegisteredUsers()){
return; //the rest of the code below should not execute
}
//if check users is true then the code below should not execute
// some other code
}
我不想返回一个承诺,我想要一个布尔值。
【问题讨论】:
-
然后把逻辑放进去
-
从
checkRegisteredUsers方法中删除then和catch回调。我建议也使用asyn/await语句来处理异步函数。 -
您是这样建议的吗:
checkRegisteredUsers = () => { return this.getUsers(); }我仍然无法设置 userChecks 的状态。我第一次点击按钮时它仍然返回 false
标签: javascript reactjs promise