我正在嘗試訪問 promise 方法中的字段。這是代碼:// Import stylesheetsimport './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()返回空。如何從 promise 方法中獲取預期的字符串?換句話說,如何this在 Promise 方法中訪問?更新:我對 Promise 的返回值沒有問題,請注意如何從返回的類方法訪問類屬性或值Promise。
TypeScript如何訪問promise方法中的字段
茅侃侃
2022-10-27 14:42:34