Returning an Axios Promise from function

两盒软妹~` 提交于 2019-11-30 00:04:08

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:

  1. In your second example, you're not passing on the resolution value, so the promise returned by your then is resolved with undefined (the return value of console.log).

  2. In your second example, you're converting rejections into resolutions with undefined (by returning the result of console.log out of catch). A catch 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; });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!