1

I'm trying to create a method, and in another method to access its return. However, when I don't return anything, the promise gives the error: then is not a function.

verifyUser() {
  if (currentUser.Title) {
    return Promise.resolve(currentUser)
  }
}

myMethod() {
  this.verifyUser
    .then(user => {
      console.log(user);
    })
}

When nothing returns, I tried to catch it, but it didn't work either

9
  • 3
    Does that not make sense? Undefined isn't a promise, it doesn't have then or catch props. Commented Apr 6, 2020 at 18:22
  • 3
    However, when I don't return anything, the promise gives the error: then is not a function. Which promise? When you don't return anything, there is no promise to call then on. Commented Apr 6, 2020 at 18:22
  • 2
    What should verifyUser do in the case when currentUser does not have Title. Throw an error, return null, … ? Commented Apr 6, 2020 at 18:22
  • 1
    Can you elaborate? The code you've shown is wrong Commented Apr 6, 2020 at 18:23
  • 1
    in verifyUser, if you don't go inside the IF, the function does not return anything... Please, rewrite your code Commented Apr 6, 2020 at 18:23

1 Answer 1

2

The correct version of your code should be something like this:

function verifyUser() {
  return new Promise((resolve, reject) => {
    if (currentUser.Title) {
      resolve(currentUser);
    } else{
      reject();
    }
  });
}

function myMethod() {
  verifyUser()
    .then(user => {
      console.log(user);
    })
    .catch(() => {});
}
Sign up to request clarification or add additional context in comments.

3 Comments

Using Promise.resolve() and Promise.reject() would be better though
If verifyUser() has no async code, then why even use a promise at all?
No, but It's just a brief version! and show the main code structure. assuming there is lots of works to do in methods ...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.