This one catches errors not only during the ajax request, but during the
onSuccess
handler execution.
const response = ajax(options).then(onSuccess).catch(onFailure)
The appropriate translation to async/await could be something like this:
try {
const response = await ajax(options)
onSuccess(response)
} catch(error) {
onFailure(error)
}
Simple and fair enough. So far so good.
However, we usually do not want to catch errors occurring inside the
onSuccess
handler. This can lead to errors difficult to catch or even
test for.
Imagine you have a bug inside your onSuccess
handler. Something that
throws an error under a certain condition. If your onFailure
handler
catches it too, in addition to catching legitimate errors during the
ajax request, you may end up with "failed" network requests that did
not actually fail.
That's why the original promise callback handler .then
supports
receiving two callbacks.
const response = ajax(options).then(onSuccess, onFailure)
Translating this one is, in my opinion, not doable in async/await clearly.
let response = undefined
try {
response = await ajax(options)
} catch(error) {
onFailure(error)
}
if (response !== undefined) {
onSuccess(response)
}
Am I missing something here? Can the above be written more clearly? I admit that my promise-accustomed brain may be slipping though.
What if, when you use
.then
, the function throws anError
(using thethrow
operator)? This is, of course, mitigated by makingajax
anasync function
.