-3

I am trying to access field in promise method.

Here is the code:

// Import stylesheets
import './style.css';
export class User{
  
  firstName:string;
  lastName:string;
  constructor(){
    this.firstName = "Tom";
    this.lastName = "Jack";
    this.getName = this.getName.bind(this);
  } 
  getName():Promise<string>{
    return new Promise((resolve,reject) =>{
      return resolve(`My Name is ${this.firstName} ${this.lastName}`);
    }) ;
  }
}

export class UserApi{
  userName:string;
  getUserName():string{
    let user = new User();
    user.getName().then(name => {
      return name;
    });
    return '';
  }
  
}
// Write TypeScript code!
const appDiv: HTMLElement = document.getElementById('app');
appDiv.innerHTML = `<h1>TypeScript Starter</h1>`;
let user = new UserApi();
appDiv.append('This is ' + user.getUserName());

user.getUserName() returns empty.

How to get the expected string from promise method?

In other words, how to access this in Promise method?

Update:

I don't have issue with return value from Promise, please pay attention to how to access class property or value from class method which is return Promise.

Edward
  • 28,296
  • 11
  • 76
  • 121

1 Answers1

1

You should return a promise from the getUserName method. Like this:

getUserName(){
    let user = new User();
    return user.getName().then(name => {
        return name;
    });
}

And if you’re just going to return the name like above, you don’t need the “then”:

return user.getName();

When you use the getUserName method you need to deal with the promise. Like so:

let user = new UserApi();
user.getUserName().then((name) => {
    appDiv.append('This is ' + name);
});
schteppe
  • 1,984
  • 13
  • 15
  • for your code, `getUserName` will throw error. – Edward Jul 02 '20 at 14:29
  • Sorry about that. What error? – schteppe Jul 02 '20 at 14:32
  • check [demo](https://stackblitz.com/edit/typescript-1avren) – Edward Jul 02 '20 at 14:34
  • Yeah. Fix the return type of getUserName and update the usage on the last line and it should work – schteppe Jul 02 '20 at 14:38
  • it returns expected result, I am wondering whether there is any way to avoid `user.getUserName().then`? – Edward Jul 02 '20 at 14:45
  • Ok, cool. I don’t think it’s possible. Asynchronous calls will always require you to use Promises all the way to the caller. You could perhaps use async/await syntax to make the code look nicer, but I’m not sure if it’s supported everywhere. – schteppe Jul 02 '20 at 14:51