Chaining thunks
olejnjak opened this issue · 3 comments
Hi,
I was wondering whether there is a recommended way how to chain thunks? The original redux-thunk works with promises while our Thunk is just a Void
closure which makes chaining a bit complicated.
Thanks in advance.
Please note the code below is pseudocode and has not been tested with a compiler.
You can easily wrap this Thunk library with a promise of some kind if you wish to use that method
let promise = Promise()
let thunk = Thunk<MyState> { dispatch, getState in
if getState!.loading {
promise.reject()
return
}
dispatch(RequestStart())
api.getSomething() { something in
if something != nil {
dispatch(RequestSuccess(something))
promise.fulfill()
} else {
dispatch(RequestError())
promise.reject()
}
}
}
store.dispatch(thunk)
promise.then { ... }
You could also write a helper function that creates a thunk with a promise and returns it via a tuple
func foo(...) -> (Thunk<MyState>, promise) { ... }
let (thunk, promise) = foo(...)
store.dispatch(thunk)
promise.then { ... }
If we want to go even further, If you wanted the full behaviour of redux-thunk
with dispatch
able to return promises, you could extend Store
to return promises when a certain type of action is passed in.
struct PromisedThunk<State>: PromisedThunk {
let promise: Promise
let thunk: Thunk<State>
// ...
}
extension Store {
func dispatch(_ thunk: PromisedThunk) -> Promise {
dispatch(thunk.thunk)
return thunk.promise
}
}
Looks OK, will try something, thanks
How to chain 2 API calls asynchronous by using thunk ? I tried using Promise but it's not available on Reswift