How to return value in then()

Viewed 10959

I know similar questions have been asked. But I will explain the difference.

I have a function called login() that needs to return a User. This function calls another function which makes a call to my backend. The login() function needs to wait for a promise to finish before returning the User. The problem is, if I put the return in the then() it will say:

[ts] A function whose declared type is neither 'void' nor 'any' must return a value.

It needs to be returned because the function calling it will need the JWT of the User.


Simplified code:

login(user: User): User {
  this.user = user;
  //in between I fill some fields for the user
  this.loginPromise().then(user => {
    return user;
  })
  .catch(err => {
    console.log(err);
    //it doesn't make a difference wether I return a user here or not
}

loginPromise(): Promise<{}> {
 var promise = new Promise(function(resolve, reject) {
  this.restProvider.login(this.user)
  .subscribe(result => {
    const jwt = result.headers.get('JWT');
    const config = { ... result.body };
    if(config['result'] != 'failed'){
      this.user.$JsonWebToken = jwt;
      this.user.$passwordIsValid = true;
      this.user.$usernameIsValid = true;
      resolve(this.user);
    }
  }, err => {
    console.log("error: " + err);
    reject(err);
  });
 })
 return promise;
}
3 Answers

You login function can't return User object directly, it has to return Promise<User> object because it gets user object asynchronously.

login(user: User): Promise<User> {
  this.user = user;
  //in between I fill some fields for the user
  return this.loginPromise()
  .catch(err => {
    console.log(err);
  });
}

And then the consumer function will call login function and use .then to get the user value retrieved from the Server.

this.login().then(
  user => console.log(user);
)

you can't return from .then, an option you can use here is to use async await, but in this case your login function will return promise, so you will need to call .then on login when you will call login function

async login(user: User): Promise<User> {
  this.user = user;

  return await this.loginPromise();
}

If you change from this loginPromise(): Promise<{}> into something simple like this loginPromise(){ I think it still returning a value

Related