拒絕承諾我有一些代碼基本上是這樣的:傳播通過.catch()
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找不到任何數據,然後拒絕該承諾併發生錯誤。然後第二個函數應該理想地捕獲這個錯誤並將其傳播到firstFunction,以便firstFunction可以正確處理該錯誤。我曾嘗試做一個throw err
a return err
和return Promise.reject(err)
所有這些導致未處理的承諾拒絕。我的(可能根本)誤解這應該如何工作?
@Tomalak是啊,沒錯,我只是沒了複製錯誤。固定。 – Bergi