Skip to content

Instantly share code, notes, and snippets.

@simmo
Created December 21, 2016 08:35
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 simmo/06e6a1a5bf3e2c018ba3ccbaf98c5bf0 to your computer and use it in GitHub Desktop.
Save simmo/06e6a1a5bf3e2c018ba3ccbaf98c5bf0 to your computer and use it in GitHub Desktop.
Redux Middleware: Cacheable Promises
// Utility to check if value is a Promise
function isPromise(value) {
if (value !== null && typeof value === 'object') {
return value && typeof value.then === 'function'
}
return false
}
// Cache
let cache = {}
export default function promiseMiddleware({ dispatch }) {
return (next) => (action) => {
// If it's not a promise, skip
if (!isPromise(action.payload)) {
return next(action)
}
// Check the cache
if (cache.hasOwnProperty(action.type)) {
// In the cache, return Promise in progress
return cache[action.type]
} else {
// Not in cache, trigger pending action
next({
type: `${action.type}_PENDING`
})
// Handle Promise resolution
const handleResolution = (error = false, payload = null) => {
// Remove from cache
delete cache[action.type]
return dispatch({
type: `${action.type}_${error ? 'REJECTED' : 'FULFILLED'}`,
payload,
error
})
}
// Add Promise to cache and return it
return cache[action.type] = action.payload.then(handleResolution.bind(null, false), handleResolution.bind(null, true))
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment