2017-05-16 50 views
0

拒絕承諾我有一些代碼基本上是這樣的:傳播通過.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 errreturn Promise.reject(err)所有這些導致未處理的承諾拒絕。我的(可能根本)誤解這應該如何工作?

回答

3

的secondFunction最好應抓住這個錯誤,並傳播它

沒有,傳播是默認的。理想情況下,你根本不需要去捕捉它,它會自動傳播。

我試過所有導致未處理的承諾拒絕的事情。我的(可能是根本性的)誤解是什麼?

您正在使用Promise constructor antipattern!有了它,你需要在catch處理程序中調用reject(err)使其工作。或者真的是.then(resolve, reject);。但是,這絕對不是如何做到這一點。

相反,放下new Promise包裝,就回到鏈接then處理結果:

export function secondFunction(id: string): Promise<UserId> { 
    return thirdFunction(id) 
    .then((data: TableInfo) => { 
    if (Object.keys(data).length !== 3) { 
     throw new Error('data in database is not mapped properly'); 
    } 
    return getUserId(data); 
    }); 
} 

export function thirdFunction(id: string): Promise<TableInfo> { 
    let query = `/* query goes here */`; 
    return db.executeQuery(query, [id]) 
    .then((data: TableInfo) => { 
    if (Object.keys(data).length < 1) { 
     throw new NoResultError('some message here'); 
    } 
    return data; 
    }); 
} 
+0

@Tomalak是啊,沒錯,我只是沒了複製錯誤。固定。 – Bergi