Express+TypeScript中async函数未正确返回值问题求助
解决方法
核心问题是混用了回调模式和Promise/async-await模式,导致返回值逻辑混乱。正确的做法是把回调风格的locationsRepo.findAll包装成Promise,再用await等待结果。
修正后的代码
public async getAll(): Promise<GeneralResponse> { try { // 将回调方法包装为Promise const locations = await new Promise<Location[]>((resolve, reject) => { locationsRepo.findAll((error: Error, locations: Location[]) => { if (error) reject(error); else resolve(locations); }); }); return { locations, error: undefined }; } catch (error) { return { locations: [], error: error as Error }; } }
问题根源解释
第一个错误的原因:
getAll方法声明返回Promise<GeneralResponse>,但方法内部仅调用了locationsRepo.findAll,未返回任何值。回调函数里的return response仅属于回调自身的返回值,和外层getAll无关,因此TypeScript提示函数必须返回值。第二个错误的原因:
locationsRepo.findAll是异步执行的,当你直接返回外层的response时,回调还未触发,response仍为初始空数组状态,自然返回空值。
额外优化(若Repo支持Promise)
如果你的locationsRepo本身支持Promise风格调用(多数ORM库都提供findAll()返回Promise的版本),可直接简化代码:
public async getAll(): Promise<GeneralResponse> { try { const locations = await locationsRepo.findAll(); return { locations, error: undefined }; } catch (error) { return { locations: [], error: error as Error }; } }
内容的提问来源于stack exchange,提问作者Patricio Palacios
相关产品推荐
相关产品推荐

