I have this situation :
import processAsyncCall from "../helpers/processAsyncCall";
const promiseWrapper = () => new Promise((res, rej) => { /* [1] */ });
const onResolve = () => { /* [2] */ };
dispatch(processAsyncCall(promiseWrapper, onResolve));
- The
promiseWrapper
contains a promise that will resolve when a certain action is made (ex: fetch a file, update content, etc.). - This method will be called when the
promise
inside thepromiseWrapper
has resolved.
Let's take a look at processAsyncCall
.
export default (
promiseWrapper,
onResolve = null,
) => (dispatch, getState) => {
dispatch(showLoading());
promiseWrapper()
.then(result => {
if (onResolve !== null && typeof onResolve === "function") {
onResolve(dispatch, getState)(result);
}
})
.catch(() => console.log("ERROR_IN_ASYNC"))
.finally(() => dispatch(hideLoading()));
});
};
The important part is promiseWrapper().then(result => { /* ... */})
.
I execute the function promiseWrapper
to create the Promise on the spot.
My question :
Is it necessary to wrap a promise in a function to ensure that it is not resolved before it is processed?
I had this problem where the then
callback wouldn't work if I passed my Promise directly as a parameter.
dispatch(processAsyncCall(new Promise(/* ... */), /* ... */));
My understanding is that when a promise resolves, the then
callback is called. But if the function resolves and there is no then
callback at that time, the Promise is done/completed/dead.
Keep in mind that the example above is pretty straightforward, but in some cases the Promise is created elsewhere and it is passed down until it reaches the processAsyncCall
function.