【发布时间】:2017-10-15 22:46:09
【问题描述】:
我有一些基本上看起来像这样的代码:
export function firstFunction(req: express.Request, res: express.Response, next: express.NextFunction): void {
secondFunction(id)
.then((userId: UserId) => {
res.status(200).send(UserId);
})
.catch((err) => {
if (err instanceof NoResultError) {
res.status(404).send(err);
} else {
next(err);
}
});
}
export function secondFunction(id: string): Promise<UserId> {
return new Promise<UserId>((resolve, reject) => {
thirdFunction(id)
.then((data: TableInfo) => {
if (Object.keys(data).length !== 3) {
reject(new Error('data in database is not mapped properly'));
}
resolve(data);
})
.catch((err) => {
// WANT TO PROPAGATE ERROR UP TO THE GETDETAILS FUNCTION WHICH CALLS THIS
});
});
}
export function thirdFunction(id: string): Promise<TableInfo> {
return new Promise<TableInfo>((resolve, reject) => {
let query = `
//query goes here
`;
db.executeQuery(query, [id])
.then((data: TableInfo) => {
if (Object.keys(data).length < 1) {
reject(new NoResultError('some message here'));
}
resolve(data);
});
});
}
我的目标是让三个函数中的最低级别 (thirdFunction) 确定来自 db-query 的数据是否找不到数据,然后以错误拒绝该承诺。然后 secondFunction 应该理想地捕获此错误并将其传播到 firstFunction 以便 firstFunction 可以正确处理该错误。我尝试过执行throw err、return err 和return Promise.reject(err),所有这些都会导致未处理的承诺拒绝。我对这应该如何工作有什么(可能是根本的)误解?
【问题讨论】:
标签: javascript node.js typescript promise