Last active
February 11, 2020 09:15
-
-
Save Freak613/0bf04e58fb2d54f026ec11072ae51740 to your computer and use it in GitHub Desktop.
This file contains 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
const createInstance = () => { | |
const queue = []; | |
return { | |
schedule: effect => queue.push(effect), | |
getQueue: () => queue | |
}; | |
}; | |
const NoOp = { | |
schedule: () => {}, | |
getQueue: () => [] | |
}; | |
let instance = NoOp; | |
const loop = (state, effect) => { | |
instance.schedule(effect); | |
return state; | |
}; | |
const withEffects = cb => { | |
const prevInstance = instance; | |
instance = createInstance(); | |
cb(); | |
const queue = instance.getQueue(); | |
instance = prevInstance; | |
return queue; | |
}; | |
const nextTick = fn => Promise.resolve().then(fn); | |
const isPromise = value => value instanceof Promise; | |
const loopMiddleware = store => next => action => { | |
const onError = store.onError || (() => {}); | |
const effects = withEffects(() => next(action)); | |
if (effects.length > 0) { | |
nextTick(() => { | |
effects.forEach(effect => { | |
try { | |
const result = effect(store); | |
if (result && isPromise(result)) { | |
result.catch(e => onError(e)); | |
} | |
} catch (e) { | |
onError(e); | |
} | |
}); | |
}); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment