Skip to content

Instantly share code, notes, and snippets.

@acodesmith
Created March 28, 2018 18:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save acodesmith/5b20715a39a47d746bf9eaa47c2e52c0 to your computer and use it in GitHub Desktop.
Save acodesmith/5b20715a39a47d746bf9eaa47c2e52c0 to your computer and use it in GitHub Desktop.
Promise all response mapped to redux actions.
export class ReduxPromiseChain {
constructor({ dispatch, promises = [], dispatchMap = [], catchFunc }) {
this.dispatch = dispatch;
this.promises = promises;
this.dispatchMap = dispatchMap;
this.error = false;
this.catchFunc = catchFunc;
if (!dispatch && typeof dispatch === 'function') {
console.error('ReduxPromiseChain requires the dispatch function!');
this.error = true;
}
}
start() {
return new Promise((resolve, reject) => {
Promise.all(this.promises)
.then(values => {
this.dispatchPayloads(values);
resolve(values);
})
.catch(reason => {
if (this.catchFunc) {
this.catchFunc(reason);
}
});
});
}
dispatchPayloads = values => {
if (!this.error) {
values.forEach((response, index) => {
switch (typeof this.dispatchMap[index]) {
case 'string':
this.dispatch({
type: this.dispatchMap[index],
payload: response,
});
break;
case 'function':
this.dispatchMap[index](response);
break;
default:
console.warn(
'Unsupported dispatchMap type. Must be a string or function.',
`Supplied: ${typeof this.dispatchMap[index]}`
);
}
});
}
return values;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment