如何在承诺中返回布尔值?

时间:2020-05-09 21:05:45

标签: javascript reactjs promise

在内部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中检查真假?

编辑:

问题是:我想检查类似这样的内容时,如何从诺言中返回布尔值:

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
}

我不希望返回承诺,我想要布尔值。

1 个答案:

答案 0 :(得分:1)

长话短说:您不能使返回promise的函数返回布尔值。如果您执行某些异步操作(例如从某项服务中获取用户的获取操作),则该操作本质上是异步的。您不能让这样的函数返回布尔值,因为到函数本身结束时,您就没有返回true或false的信息。

您可以使用async / await获得最接近的结果。但是异步函数仍然只返回Promise对象。您可以使用async / await使它看起来不同,但这只是语法糖。在await之后,您仍然可以有效地运行所有代码,就像它是传递给then的函数一样。

例如,

//Some function that will resolve or reject.
const getUsers = () {
  return new Promise(function (resolve, reject) {
    resolve(5);
  });
}
const foundUsers = async () => {
  const users = await getUsers();
  return Boolean(users);
}
const LoggedIn = () => {
  const [usersFound, setUsersFound] = useState(false)
  const onSubmit = async () => {
    const found = await foundUsers();
    if (found) {
      //do stuff
    }
    setUsersFound(found)
  }
  return (
    <>
      <button onClick={onSubmit}>Submit</button>
      { usersFound ? <Dialog /> : <WhateverElse /> }
    </>
  )
}

与此相同:

const LoggedIn = () => {
  const [usersFound, setUsersFound] = useState(false)
  const onSubmit = () => {
    foundUsers().then((found) => {
      if (found) {
        //do stuff
      }
      setUsersFound(found)
    })
  }
  return (
    <>
      <button onClick={onSubmit}>Submit</button>
      { usersFound ? <Dialog /> : <WhateverElse /> }
    </>
  )
}