Advertisement
Guest User

Untitled

a guest
Jul 20th, 2017
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.36 KB | None | 0 0
  1. // runs on load
  2. export function* main() {
  3. const pollingInstance = yield fork(pollingWatcher);
  4. // fork other watchers ...
  5.  
  6. // if location changes, kill the watcher(s)
  7. yield take(LOCATION_CHANGE);
  8. yield cancel(pollingInstance);
  9. // cancel other watchers ...
  10. }
  11.  
  12.  
  13. // Listen for every START and fork off saga that will start/stop polling
  14. export function* pollingWatcher() {
  15. yield fork(takeEvery, START, pollRacer);
  16. }
  17.  
  18.  
  19. export function* pollRacer(raceAction) {
  20. const { response, cancelPolling } = yield race({
  21. response: call(pollingSaga, raceAction),
  22. cancelPolling: take(action => (action.type.endsWith('CANCEL') && action.payload.data.id === raceAction.payload.data.id))
  23. });
  24. }
  25.  
  26.  
  27. // try polling every 3 seconds until the server completes or errors out
  28. // put success or failure actions
  29. export function* pollingSaga(action) {
  30. try {
  31. const { id } = action.payload.data;
  32.  
  33. let status = 'p';
  34. let pollResponse;
  35.  
  36. while (status !== 'complete') {
  37. yield call(delay, 3000);
  38. pollResponse = yield call(request, someUrl, id);
  39. status = pollResponse.data && pollResponse.data.status;
  40. if (status === 'error') throw new Error('Runtime error');
  41. }
  42.  
  43. yield put(pollSuccess(pollResponse.data));
  44. } catch (error) {
  45. yield put(pollFailure(error));
  46. } finally {
  47. if (yield cancelled()) {
  48. console.log('pollingSaga cancelled');
  49. }
  50. }
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement