简体   繁体   English

使用 redux thunk 的动作创建者和普通的异步函数之间的区别

[英]Difference between an action creator using redux thunk and a normal async function

So I want to understand beyond the basics of Redux thunk and I made two action creators, one of which works and uses redux thunk and other which only uses async but breaks.Below is the screenshot:所以我想了解 Redux thunk 的基础知识之外,我制作了两个动作创建器,一个可以工作并使用 redux thunk,另一个只使用异步但中断。下面是截图:

截屏

So in both action creators I await for the API request to finish and then return an action ( a JS object with type and payload).因此,在两个动作创建者中,我都等待 API 请求完成,然后返回一个动作(具有类型和负载的 JS 对象)。

However only the top one works and the bottom one gives an error saying action must be plain object although I return a plain object with 2 properties.但是,只有顶部一个有效,底部一个给出错误,指出 action 必须是普通对象,尽管我返回了一个具有 2 个属性的普通对象。 I've been really struggling to understand why does the second action creator brakes and would be really nice if someone could explain in details why is it happening.Thank you!我一直在努力理解为什么第二个动作创建者会刹车,如果有人能详细解释为什么会这样,那就太好了。谢谢!

It is because, when you use thunk, you return either an object or function.这是因为,当您使用 thunk 时,您将返回一个对象或函数。 In 2nd case, when you dispatched your actions something like this dispatch(fetchUser()) , it didn't return any thing because you are calling an async method.dispatch(fetchUser())情况下,当您调度类似dispatch(fetchUser()) ,它没有返回任何内容,因为您正在调用异步方法。 Now code below await will only be executed once async all is done, original call of dispatch(fetchUser()) is already completed (hint : Only code below await is not executed, but the function call is already over), and fetchUser() didn't return any object, but in first case, you are actually returning a function which is calling an async method.现在 await 下面的代码只有在 async all 完成后才会执行,原始调用dispatch(fetchUser())已经完成(提示:只有 await 下面的代码没有执行,但函数调用已经结束),以及fetchUser()没有返回任何对象,但在第一种情况下,您实际上正在返回一个调用异步方法的函数。 This is where the magic of thunk middleware really happens.这就是 thunk 中间件的神奇之处。 It executes that function and dispatch an action (hint: you are returning a function which is taking dispatch as an argument) which is executed by thunk.它执行该函数并分派一个由 thunk 执行的动作(提示:您正在返回一个将分派作为参数的函数)。 Hope this clears your doubt.希望这可以消除您的疑虑。 I would suggest you to read how async/await really works (hint : event loops/single threaded).我建议您阅读 async/await 的真正工作原理(提示:事件循环/单线程)。

You cant use an async function because it will always returns a promise.你不能使用异步函数,因为它总是会返回一个承诺。 Even if you return a value it will be wrapped in a promise and it is returned.即使你返回一个值,它也会被包装在一个承诺中并被返回。 If you dont return anything in async function and try to read the value , then undefined will be wrapped in a promise .如果在 async 函数中没有返回任何内容并尝试读取值,则 undefined 将被包装在一个 promise 中。 As redux says action creators should return a plain object which cannot be done directly using async functions.正如 redux 所说,动作创建者应该返回一个不能直接使用异步函数完成的普通对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM