Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return value in then()

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;
}
like image 789
Puremonk Avatar asked Oct 24 '25 02:10

Puremonk


2 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);
)
like image 115
Pankaj Parkar Avatar answered Oct 26 '25 16:10

Pankaj Parkar


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();
}
like image 38
Artyom Amiryan Avatar answered Oct 26 '25 17:10

Artyom Amiryan