简体   繁体   English

Function即使通过也不返回true

[英]Function does not return true even if it goes through

I can't seem to make this work but I want to return true every-time the function executes successfully, which in this case is "Changing the password".我似乎无法完成这项工作,但我想在每次 function 成功执行时返回 true,在本例中为“更改密码”。

async function ChangePassword(data) {
  const auth = getAuth();
  let res = false;
  const credential = EmailAuthProvider.credential(
    auth.currentUser.email,
    data.oldPassword
  );
  reauthenticateWithCredential(auth.currentUser, credential)
    .then(() => {
      updatePassword(auth.currentUser, data.password)
        .then(() => {
          toast.success("Password changed successfully");
          res = true;
          console.log("res ",res);
        })
        .catch((error) => {
          toast.error(error.message);
        });
    })
    .catch((error) => {
      toast.error(error.message);
    });
  return res;
}

The res variable when called by other functions always results in false even though I see the toast message "Password changed successfully". res 变量在被其他函数调用时总是返回false ,即使我看到 toast 消息“密码更改成功”也是如此。

async function changePassword() {
    if (password === "" || confirmPassword === "" || oldPassword === "") {
      toast.error("Please fill all the fields");
    } else if (password !== confirmPassword) {
      toast.error("Passwords do not match");
    } else {
      let data = { oldPassword, password };
      await ChangePassword(data).then((res) => {
        if (res === true) {
          setChangePasswordModal(false);
          setOpen(false);
        }
      });
    }
  }

The if condition in above code never executes because res is always false.上面代码中的 if 条件永远不会执行,因为res始终为 false。 I know it has something to do with async await but can't figure out how to make it work我知道它与 async await 有关,但不知道如何让它工作

async function ChangePassword(data) {
  const auth = getAuth();
  let res = false;
  const credential = EmailAuthProvider.credential(
    auth.currentUser.email,
    data.oldPassword
  );
  reauthenticateWithCredential(auth.currentUser, credential)
    .then(() => {
      updatePassword(auth.currentUser, data.password)
        .then(() => {
          toast.success("Password changed successfully");
          res = true;
          console.log("res ",res);
        })
        .catch((error) => {
          toast.error(error.message);
        });
    })
    .catch((error) => {
      toast.error(error.message);
    });
  return res;
}

Has many logical errors in it.里面有很多逻辑错误。

First you should decide whether you're going to use async and its feature await or classical Promise .then able -style.首先,您应该决定是要使用async及其特性await还是经典的 Promise .then able 风格。 Please do not use both, it will only confuse you and the reader.请不要同时使用两者,这只会让您和读者感到困惑。

Let's ditch the async (since you don't even use await ), and Promise s are chainable, you do not (and MUST not) nest .then blocks, use this instead:让我们放弃异步(因为你甚至不使用await ),并且Promise是可链接的,你不(也不能)嵌套.then块,而是使用它:

function ChangePassword(data) {
  const auth = getAuth();
  const credential = EmailAuthProvider.credential(auth.currentUser.email, data.oldPassword);

  return reauthenticateWithCredential(auth.currentUser, credential)
  .then(() => {
      return updatePassword(auth.currentUser, data.password)
  })
  .then(() => {
      toast.success("Password changed successfully");

      return true;
  })
  .catch((error) => {
      toast.error(error.message);

      return false;
  })
}

The key here is that ChangePassword itself returns a Promise.*这里的关键是ChangePassword本身返回一个 Promise.*

The caller is then responsible to call it with .then or use async in combination with await :然后调用者负责使用.then调用它或结合使用asyncawait

ChangePassword({/* data */}).then((result) => {
    console.log("ChangePassword done", result)
})

The same code looks a lot cleaner if you use async :如果您使用async ,相同的代码看起来更清晰:

async function ChangePassword(data) {
  const auth = getAuth();
  const credential = EmailAuthProvider.credential(auth.currentUser.email, data.oldPassword);

  try {
    await reauthenticateWithCredential(auth.currentUser, credential);
    await updatePassword(auth.currentUser, data.password);
    toast.success("Password changed successfully");

    return true;
  } catch (error) {
    toast.error(error.message);

    return false;
  }
}

(If you were wondering how that would look like). (如果您想知道那会是什么样子)。

*a function tagged as async ALWAYS returns a promise, by the way. * 顺便说一句,标记为async的 function总是返回 promise。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Flutter Firebase authStateChanges 快照始终返回真值,即使用户已删除 - Flutter Firebase authStateChanges Snapshot Always Return True Even User Deleted Function 即使使用有效 ID 也始终返回 false - Function always return false even with a valid ID setDoc function 返回什么? - What does setDoc function return? SQS - 即使将 maxNumberOfMessages 设置为 1,所有消息都会发送 - SQS - all messages goes into flight even when maxNumberOfMessages is set to 1 为什么我的 function 调用 API 或启动协程返回空值或 null 值? - Why does my function that calls an API or launches a coroutine return an empty or null value? 为什么 persistenceEnabled: true 导致我的查询给出不正确的结果? - Why does persistenceEnabled: true result in my queries giving incorrect results? 当引用更改并变为空白时,FirebaseUI RecyclerView 不会更新 - FirebaseUI RecyclerView does not update when reference is changed and goes blank 从 reactjs 中的 function 返回一个字符串 - return a string from a function in reactjs Lambda function 未退出但正在记录返回 - Lambda function is not exiting but is logging the return 在 React 中,return 语句是立即返回还是等待 UseEffect 完成? - In React, does a return statement return immediately or does it wait for the UseEffect to finish?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM