Let’s say I have something like:
const exampleFunction = () => {
const fetchActions = someArray.map(() => {
dispatch(action()).then(response => {
if (response?.data) {
dispatch(subAction({response: response.data}))
}
})
})
return Promise.all(fetchActions)
.then(()=> dispatch(finalAction()))
}
My problem is that when I dispatch my finalAction, all the actions have been dispatched/resolved but not the subActions. How can I execute my dispatch(finalAction())) ONLY when all the actions and subActions have been resolved?
2
Answers
The problem with your code is that you are not returning anything from the
someArray.map
callback, which means thatfetchActions
is an array of undefined values, not promises. Therefore,Promise.all
will not wait for the dispatch actions or subActions to finish before resolving.To fix this problem, you can try this:
In this code,
someArray.map
doesn’t return anything, but it makes an array of promises. Each promise waits for the last await inside the map function, which is eitherdispatch(subAction())
orundefined
. It’s like returning an array of those values as promises.If you want to make it more explicit, you can add a return statement inside the map callback, like this:
The problem is
Promise.all([...promises])
resolves when allpromises
resolve but yourfetchActions
is not really an array of promises (that you intended) because they have orphaned promises with the promise chain disconnected. In order to connect the chain again, you need to addreturn
.See here to learn more about promise chaining.
Basically, the idea is: if you want a function to resolve after the promise called inside it is resolved, you need to
return
that promise.For example:
Promise.all
above immediately resolves without waiting forpromiseY
orpromiseZ
because they’re orphaned promises.In order to wait for them, it should be like this: