Last active
October 31, 2020 06:51
-
-
Save truongluu/e584cd9bcd97cdc68e12a45f27677bef to your computer and use it in GitHub Desktop.
Saga Promise Helpers
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
import { put } from 'redux-saga/effects'; | |
export const withPromiseAndDispath = (func, params, dispacth) => | |
new Promise((resolve, reject) => | |
dispacth(func({ ...params, resolve, reject })) | |
); | |
export const startActionWithPromise = (action, params, dispatch) => { | |
return withPromiseAndDispath(action?.start, { ...params, actionMeta: action }, dispatch); | |
} | |
function resoveResult(action, result) { | |
if (action?.resolve && typeof action.resolve === 'function') { | |
action.resolve(result); | |
} | |
if (action?.successCallback && typeof action.successCallback === 'function') { | |
action.successCallback(result); | |
} | |
} | |
function rejectResult(action, result) { | |
if (action?.reject && typeof action.resolve === 'function') { | |
action.resolve(result) | |
} | |
if (action?.failedCallback && typeof action.failedCallback === 'function') { | |
action.failedCallback(result); | |
} | |
} | |
export function sagaPromise(handler) { | |
return function* (action) { | |
try { | |
const result = yield* handler(action); | |
if (action?.payload?.actionMeta.success) { | |
yield put(action.payload.actionMeta.success(result)); | |
} | |
resoveResult(action?.payload, result); | |
} catch (error) { | |
if (action?.payload?.actionMeta.error) { | |
yield put(action.payload.actionMeta.error(error)); | |
} | |
rejectResult(action?.payload, error); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment