有人可以幫我弄清楚我做錯了什么嗎?在繼續執行我的函式之前,我想先檢查檔案是否存在,如果不存在,則拋出錯誤。但是那個錯誤永遠不會被發現?這是我想拋出錯誤的函式:
class StoreGateway {
async addCustomerToStore(
customerId: string
) {
const customer = await fb.customersCollection.doc(customerId).get();
if (customer.exists) {
//do other stuff
} else {
console.log("customer didn't exist")
return new Error("customer didn't exist");
}
}
}
以及我如何呼叫該函式:
StoreGateway.addCustomerToStore(
req.params.customerId
)
.then(() => {
res
.status(200)
.json("Success");
})
.catch((err) => {
res.status(500).json(err);
});
}
現在,如果檔案不存在,控制臺會列印“客戶不存在”,但我永遠不會得到狀態 500。
uj5u.com熱心網友回復:
問題是你只是回傳一個錯誤而不是拒絕承諾。您可以按照以下兩種方法拒絕承諾。
1. 拋出新錯誤
if (customer.exists) {
//do other stuff
} else {
console.log("customer didn't exist")
throw new Error("customer didn't exist");
}
2. 回傳一個被拒絕的 promise
if (customer.exists) {
//do other stuff
} else {
console.log("customer didn't exist")
return Promise.reject(new Error("customer didn't exist"));
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/315200.html
標籤:打字稿 火力基地 谷歌云firestore 承诺
