什么是"dispatch()"?意思/是,为什么当我们有.then()和.catch()时使用它 [英] What does "dispatch()" mean/do, and why is it used when we have .then() and .catch()

查看:1055
本文介绍了什么是"dispatch()"?意思/是,为什么当我们有.then()和.catch()时使用它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是ES6和高级javascript的新手.我已经看到了使用axios http客户端的代码示例,如下所示:

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)))

我在做什么:

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

我试图在MDN上查找调度,但只发现DispatchEvent ...这是不一样的吗?我问是因为尽管我的代码有效,但是我发现来自我的api的HTTP错误代码(如403等)被axios视为错误,而我希望自己在应用程序中处理它们. (更新:当我向这个问题添加调度标签时,我看到了含义的简短摘要,但我仍然感到困惑).

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).

使用调度的原因或优势是什么?是axios,ES6或nodejs的"dispatch()"部分吗? thx.

推荐答案

当我看到dispatch时,我立即想到了 Redux 的流行中间件).这是为什么传递dispatch有用的一个很好的例子.基本上dispatch用作回调,一旦完成一些异步操作,该回调就会被调用.在redux-thunk中,dispatch只是一个函数,该函数在您从api(异步)获取数据之后,将操作分派到Redux存储.您可以将任何您喜欢的函数传递给某个Promise的.then().catch(),并且在失败成功时将调用该函数.

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.

这篇关于什么是"dispatch()"?意思/是,为什么当我们有.then()和.catch()时使用它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆