Created
March 28, 2018 18:44
-
-
Save acodesmith/5b20715a39a47d746bf9eaa47c2e52c0 to your computer and use it in GitHub Desktop.
Promise all response mapped to redux actions.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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