Promisify Fetch Redux Action Example

Using promises to split or submit parallel ajax fetch statements from a Redux Action

First create the general promise handler all this does is resolve the promise contract function by what it is passed.

function promiseFetch(url) {
 return new Promise((resolve, reject) => {
 fetch(encodeURI(url), Request.GET)
 .then(response => {
		 if (response.ok) {
		 response.json()
		 .then(data => resolve(data))
		 .catch(error => reject(error.message));
		 } else {
		 reject(\"Network response was not ok.\");
		 }
	 })
	 .catch(error => reject(error.message));
	 });
};

Now call all the promises as once by creating them first and then using the Promise.all(arrayOfPromises)

Make sure to pass the individual item handlers to the expected promise function handlers i.e. the proper dispatches. Β In this case if any of the list of promises fail then the entire Promises.all action will result in an exception and failure

export function FetchAll() {
 const that = this;
 const urls = allUrls();
 var promises = urls.map(promiseFetch);
 return function(dispatch) {
 dispatch(individualRequest());
 Promise.all(promises)
 .then(results => dispatch(individualReceive(results)))
 .catch(error => dispatch(individualFailed(error)));
 };
};

Rest of the functions specified

Flat map recursive function

const flatMap = arr => arr.reduce((acc, val) => acc.concat(Array.isArray(val) ? flatMap(val) : val), []);

Single Request Redux Function

function individualRequest() { return { type: Type.IND_REQUEST };};

Single Receive Redux Function

function individualReceive(data) {
 const features = flatMap([].concat(data.map(z => z.items.features)));
 return {
 type: Type.IND_RECEIVE,
 data: features
 };
};

Single Failed Redux Function

function individualFailed(message) { return { type: Type.IND_FAILED, message };};