Returning an Axios Promise from function
Your first example returns the original promise. Your second example returns a different promise, the one created by calling catch
.
The critical differences between the two are:
In your second example, you're not passing on the resolution value, so the promise returned by your
then
is resolved withundefined
(the return value ofconsole.log
).In your second example, you're converting rejections into resolutions with
undefined
(by returning the result ofconsole.log
out ofcatch
). Acatch
handler that doesn't throw or return a promise that's rejected converts a rejection into a resolution.
One of the key things about promise chains is that they transform the result; every call to then
or catch
creates a new promise, and their handlers can modify what's sent downstream as the result passes through them.
The usual pattern would indeed be to return the result of the chain, but for the functions in the chain to either intentionally transform the result or pass it on. Normally, you wouldn't have a catch
handler except at the terminal end of the chain, unless you're using it to correct the error condition (intentionally converting a rejection into a resolution).
If you wanted to just log what passed through while still allowing callers to see it but did want to return the result of the chain for whatever reason, you'd do this:
return request
.then(result => { console.log(result); return result; })
.catch(error => { console.error(error); return Promise.reject(error); });
or using throw
:
return request
.then(result => { console.log(result); return result; })
.catch(error => { console.error(error); throw error; });