Search code examples
javascripttypescriptpromisees6-promise

TypeScript How to access field in promise method


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.


Solution

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