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;
}