What does “dispatch()” mean/do, and why is it used when we have .then() and .catch()

Deadly 提交于 2019-12-12 21:05:45

问题


I am new to ES6 and advanced javascript. I have seen examples of code using the axios http client like this:

axios.xxx(...).then((res) => dispatch(success(res)) , (err)=> dispatch(error(err)))

whereas I am doing:

axios.xxx(...).then(function(res){...}).catch(function(err){...});

I tried to look up dispatch on MDN but only found DispatchEvent... which is not the same? I ask because although my code works, I am finding http error codes like 403 etc from my api are handled as errors by axios, while i would prefer to handle them myself in the app. (Update: when I added the dispatch tag to this question, I saw a brief summary of the meaning but I am still confused).

What is the reason or advantage for using dispatch? Is "dispatch()" part of axios, or ES6, or nodejs? thx.


回答1:


When I see dispatch I immediately think of redux-thunk (a popular middleware for Redux). It is a good example of why passing dispatch is useful. Basically dispatch is used as a callback which gets invoked once some async action is complete. In redux-thunk dispatch is simply a function which dispatches an action to the Redux store after, let's say, you fetch data from an api (which is asynchronous). You can pass any function you like to .then() or .catch() of some Promise and it will be invoked upon success of failure.



来源:https://stackoverflow.com/questions/47002774/what-does-dispatch-mean-do-and-why-is-it-used-when-we-have-then-and-cat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!