Patrickkx
Patrickkx

Reputation: 1870

Advantages of using race in sagas

I have a pattern in my app regarding redux-saga, that for asynchro calls I have two functions - the first one is listening to some specified action and the second one is making the call to the api.

  1. Listener function:

    function* userJoinListener() {
       while (true) {
          const { user } = yield take(UserJoinRequest);
    
          const promiseRace = yield race({
             res: call(userJoinFunction, user),
             err: take(UserJoinError),
          });
    
          if (promiseRace.res) {
            // code if success
          } else {
            // code if fail
          }
       }
    }
    
  2. Api call executing function:

    function* userJoinFunction(user) {
       try {
          return yield call(userJoin, user);
       } catch (err) {
          yield put(userJoinFail);
       }
    }
    

My question is: what is the advantage of using race here exactly? To be honest, I could just use that second function in the same place as race is and it would work as expected:

function* userJoinListener() {
   while (true) {
      const { user } = yield take(UserJoinRequest);

      try {
         // code if success
         return yield call(userJoin, user);
      } catch (err) {
         // code if fail
         yield put(userJoinFail);
      }
   }
}

Thank you :)

Related question: Difference between Promise.race() and try/catch in redux-saga

Update:

Advantages:

Upvotes: 4

Views: 2256

Answers (1)

Martin Kadlec
Martin Kadlec

Reputation: 4975

Indeed using race here is unnecessary complex.

If you are handling errors or cancellation inside the called saga (userJoinFunction) itself, then just use try..catch/cancel as that is more straightforward.

If on the other hand you need to cancel the saga when something happens from the outside (timeout, user action) then it makes sense to use the race effect.

Upvotes: 4

Related Questions