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
.