Skip to content

Instantly share code, notes, and snippets.

@Freak613
Last active February 11, 2020 09:15
Show Gist options
  • Save Freak613/0bf04e58fb2d54f026ec11072ae51740 to your computer and use it in GitHub Desktop.
Save Freak613/0bf04e58fb2d54f026ec11072ae51740 to your computer and use it in GitHub Desktop.
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