我有一個運行 NodeJS 和 Express 的簡單 Web 應用程式。它有一個路由,外部 3rd 方可以向我們發送一個 XML 檔案,然后我們將其轉換為 JSON,然后保存到我們的 MongoDB 資料庫中。一些事情可能會出錯:
XML 可能格式錯誤
請求可能為空
外部的第三者可能會向我們發送重復的檔案
與其擁有無休止的一系列 then() 塊,越來越深,縮進越來越深,我想為每個可能的錯誤拋出一個例外,然后在頂層捕獲這些錯誤并在那里處理它們。
所以我們找到一個唯一的 id,然后檢查這個唯一的 id 是否已經在 MongoDB 中:
// will throw an error if there is a duplicate
document_is_redundant(AMS_945, unique_id);
該函式如下所示:
function document_is_redundant(this_model, this_unique_id) {
return this_model.findOne({ unique_id : this_unique_id })
.exec()
.then((found_document) => {
// 2021-11-28 -- if we find a duplicate, we throw an error and handle it at the end
// But remember, we want to return a HTTP status code 200 to AMS, so they will stop
// re-sending this XML document.
if (found_document != 'null') {
throw new DocumentIsRedundantException(this_unique_id);
}
});
// no catch() block because we want the exception to go to the top level
}
這給了我: UnhandledPromiseRejectionWarning
也許我想得太像 Java 而不是 Javascript,但我假設如果我沒有在該函式中 catch() 例外,它會冒泡到頂層,這就是我想要處理的地方. 還假設它會在我呼叫函式的那一行中斷代碼流。
遺憾的是,未捕獲的例外不會中斷執行的主執行緒,因此即使檔案是重復的,也會保存檔案。
所以我想我能完成這項作業的唯一方法是從函式回傳 Promise,然后在呼叫document_is_duplicate函式后有一個 then() 塊?
我不喜歡在 then() 塊中嵌套 then() 塊,深度有幾個層次。這似乎是糟糕的代碼。還有其他方法嗎?
uj5u.com熱心網友回復:
如果您的檔案存在,不確定為什么要拋出錯誤。尋找它,Mongoose 將回傳一個檔案,如果它存在,或者null如果它不存在。然后簡單await的結果。可以等待 Mongoose 方法,如果添加.exec()它們,它們甚至會回傳一個真正的 Promise,這讓您的生活更加輕松:
const document_is_redundant = (this_model, unique_id) => this_model.findOne({ unique_id }).lean().exec();
// Now you use it this way
if( !(await document_is_redundant(AMS_945, unique_id))){ // If the returned value is not null
console.log("Document is redundant! Aborting")
return;
}
// Returned value was null
console.log("The document doesn't exist yet!")
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/369190.html
標籤:javascript 承诺
