我有一個帶有多個承諾鏈的代碼,如下所示
.then(function(response) {
//my code
})
.then(function(app) {
//my code
})
.then(function() {
//my code
})
如下所示為它們中的每一個添加了例外處理,以便如果一個中斷鏈繼續。
這是處理多個鏈塊例外的正確方法,還是可以遵循任何最佳實踐來處理例外,以便代碼執行失敗時不會中斷。
.then(function(response) {
//my code
})
.catch(e => {})
.then(function(app) {
//my code
})
.catch(e => {})
.then(function() {
//my code
})
.catch(e => {})
uj5u.com熱心網友回復:
如果您的代碼可以適應早期發生的錯誤(無論它是什么),這可能是一種合理的方法,但我總是必須在代碼審查中仔細查看它,因為代碼相當不尋常能夠忽略這樣的錯誤。代碼大致相當于:
try {
//my code
} catch (e) {
}
try {
//my code
} catch(e) {
}
try {
//my code
} catch(e) {
}
...但改用承諾。所以這是一個有點懷疑,但可以是正確的,對于上述同樣的原因是有點懷疑,但可以是正確的,如果你需要同時做的一系列事情,一個,并讓每個人做到即使前一個失敗。
請注意,這意味著app在隨后的履行處理程式中將是undefined:
.then(function(response) {
//my code
})
.catch(e => {})
.then(function(app) { // <=== `app` is `undefined` here
//my code
})
.catch(e => {})
.then(function() {
//my code
})
.catch(e => {})
uj5u.com熱心網友回復:
我只想插入我的 2 美分。
你可以用一個輔助函式來獲得一些樂趣(或者使用更花哨的東西,比如包中的整個Either monad東西fp-ts)
const run = async (fn) => {
try {
const result = await fn()
return [result, null]
} catch (err) {
return [null, err]
}
}
并在沒有try\catch或的情況下撰寫代碼.then\.catch
const [response, error] = await run(() => fetch('asdfasdf'))
const app = buildApp(response.ok ? await response.json() : { fallback: 'data' })
const [appResponse, appError] = await run(async () => {
await app.compileTemplate()
return app.buildResponse()
})
if (appResponse) {
// ...
}
或者更無用的方法,您可以拋出自定義錯誤,因此您的第一個.catch塊將能夠執行某些操作。
class AppFromResponseError extends Error {
constructor(message, fallbackApp) {
super(message)
this.name = "ResponseError"
this.app = "fallbackApp"
}
}
builder
.then(function(response) {
if (response.ok !== true)
throw new AppFromResponseError('not ok', minimalApp)
})
.catch(e => {
if (e.app) return e.app
})
.then(app => { /* some kind of app will be here */})
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/310028.html
標籤:javascript 节点.js
