Promise未解析完成即调用外部API,如何在EmployeeService中处理?
问题分析与解决方案
为什么用了await的方法仍返回Promise?
所有被async关键字标记的函数,无论内部是否使用await,都会将返回值自动包装为Promise对象。比如:
async function test() { return 1; } // 实际返回 Promise.resolve(1)
你的getAttendanceHistory和#getAccountsDepartmentHistory都是async方法,所以它们的返回值必然是Promise,哪怕内部用了await等待异步操作完成。
如何在EmployeeService内部完成Promise解析?
核心问题是getData是同步方法,直接将getAttendanceHistory返回的Promise赋值给了attendance,没有等待其解析。要在EmployeeService内部完成解析,需要将getData改为async方法,在内部等待getAttendanceHistory的结果:
修改后的EmployeeService代码
class EmployeeService { constructor() { this.employeeRepository = new EmployeeRepository(); } // 改为async方法,内部await异步操作 async getData(employeeId, department) { return { name : 'John Doe', attendance : await this.getAttendanceHistory(employeeId, department) }; } async getAttendanceHistory(employeeId, department) { if (department === 'accounts') { return await this.#getAccountsDepartmentHistory(employeeId); } } async #getAccountsDepartmentHistory(employeeId) { const cursor = await this.employeeRepository.getHistory(employeeId); const messages = await cursor.toArray(); // 修正笔误:原代码中this.employeeService应为this return messages.map((entry) => this.processHistory(entry)); } }
对应调整上层调用(EmployeeRecordsService)
因为getData现在返回Promise,上层的sendData必须等待其解析,所以也要改为async方法:
class EmployeeRecordsService { constructor() { this.employeeService = new EmployeeService(); this.apiService = new ApiService(); } async sendData() { const data = await this.employeeService.getData('123', 'accounts'); const response = await this.apiService.send(data); return response; } }
关键说明
- 异步操作无法强行转为同步,必须通过
async/await或Promise.then()处理异步结果。 - 原代码中
#getAccountsDepartmentHistory里的this.employeeService.processHistory属于笔误,应改为this.processHistory,因为processHistory是EmployeeService自身的方法。
内容的提问来源于stack exchange,提问作者s.khan
相关产品推荐
相关产品推荐

