Do not fail whole task even if one of promises rejected
Asked Answered
K

3

7

In redux saga if we want to handle multiple promises, we can use all (which is equivalent of Promise.all):

yield all(
   users.map((user) => call(signUser, user)),
);

function* signUser() {
   yield call(someApi);
   yield put(someSuccessAction);
}

The problem is, even if one of the promises (calls) fail, the whole task is cancelled.

My goal is to keep the task alive, even if one of the promises failed.

In pure JS I could handle it with Promise.allSettled, but whats the proper way to do it in redux saga?

Edit: still didnt find any suitable solution, even if I wrap the yield all in try... catch block, still if even one of the calls failed, whole task is canceled.

Kennith answered 27/8, 2020 at 15:36 Comment(15)
Does this answer your question? Wait until all promises complete even if some rejectedKevyn
@Kevyn Thanks! But Im looking for a specified solution for redux sagaKennith
The principle will be the same even if the syntax differs slightly.Kevyn
@Kevyn Not really, sagas are held on generatorsKennith
Patrickkx, what does that mean, can you give me a reference?Kevyn
@Kevyn developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…Kennith
Let us continue this discussion in chat.Kevyn
You can wrap all with try/catch blockRecreant
@AlekseyL. still cancels whole task if even one promise rejectedKennith
@Patrickkx, how did you wrapped yield all with try catch?Cida
@LuisPauloPinto like Aleksey recommendedKennith
sorry, let me be more clear. Did you add try/catch involving yield all or call(signUser, user)Cida
@LuisPauloPinto Just wrapped whole yield all in try catchKennith
@Kennith Please edit this sandbox so I'll be able to reproduce the issue. Currently try/catch works as expected. There must be some missing details hereRecreant
Your question is very nice, thanks.Nomothetic
N
3

Actually, you should change your array of Promises to the all method of Redux-Saga, you should write it like below:

yield all(
  users.map((item) =>
    (function* () {
      try {
        return yield call(signUser, item);
      } catch (e) {
        return e; // **
      }
    })()
  )
);

You pass a self-invoking generator function with handling the error and instead of throw use return. hence, the line with two stars(**).

By using this way all of your async actions return as resolved and the all method never seen rejection.

Nomothetic answered 1/9, 2020 at 20:24 Comment(3)
Dear @Patrickkx, I change whole the answer and use another way.Nomothetic
You could define and use call wrapper instead of self-invoking generator. A bit cleaner codesandbox.io/s/…Recreant
Dear @AlekseyL. , Thanks for your lovely comment, even I check the CodeSandBox and I think your code is a little hight level than mine, thanks a lot, but I prefer to have my answer, for appreciate I leave some upvotes to your current correct answers.🌹Nomothetic
P
1

You can implement it by yourself. There is a PR. See below example:

import { all, put, call, takeLatest } from 'redux-saga/effects';
import { createStoreWithSaga } from '../../utils';

const someSuccessAction = { type: 'SIGN_USER_SUCCESS' };

function someApi(user) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (user < 5) {
        resolve('success');
      } else {
        reject('failed');
      }
    }, 1000);
  });
}

const allSettled = (effects) =>
  all(
    effects.map((effect) =>
      call(function* settle() {
        try {
          return { error: false, result: yield effect };
        } catch (err) {
          return { error: true, result: err };
        }
      }),
    ),
  );

function* batchSignUser(action) {
  const r = yield allSettled(action.payload.users.map((user) => call(signUser, user)));
  console.log(r);
}

function* signUser(user) {
  const r = yield call(someApi, user);
  yield put(someSuccessAction);
  return r;
}

function* watchBatchSignUser() {
  yield takeLatest('SIGN_USER', batchSignUser);
}
const store = createStoreWithSaga(watchBatchSignUser);

const users = [1, 2, 3, 4, 5, 6, 7];
store.dispatch({ type: 'SIGN_USER', payload: { users } });

The execution result:

[
  { error: false, result: 'success' },
  { error: false, result: 'success' },
  { error: false, result: 'success' },
  { error: false, result: 'success' },
  { error: true, result: 'failed' },
  { error: true, result: 'failed' },
  { error: true, result: 'failed' }
]
Pasty answered 25/6, 2021 at 11:41 Comment(0)
S
0

I was able to do it the old school way Promise.allSettled()!

const promises = [];
users.map((user) => promises.push(call(signUser, user)));


function* signUser() {
  let responses = [];
  responses = yield(yield Promise.allSettled(promises)));
  // filter the onces which are successfull unsuccessfull once don't have value
  responses = responses.filter(response => response.value);
}
Scabby answered 6/5, 2022 at 4:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.