4

It's about 5 months that I work with redux-saga, it's a great and strong middleware library.

I know almost everything in redux-saga, but I couldn't still understand "cps".

Can anyone explain me (with an example) what can be done with "cps"?

I really appreciate if someone takes me out of this confusion.

Amir Gorji
  • 2,809
  • 1
  • 21
  • 26

1 Answers1

5

cps effect is there to easily handle asynchronous functions that receive a nodejs style callback as last parameter.

const doSomething = (param1, param2, callback) => {
  setTimeout(() => {
    callback(null, 'done')
  }, 1000)
}

function* saga() {
  const result = yield cps(doSomething, 'foo', 'bar')
  console.log(result) // 'done'
}

Documentation: https://redux-saga.js.org/docs/api/#cpsfn-args

Martin Kadlec
  • 4,702
  • 2
  • 20
  • 33
  • So it's being done once the function terminates and callback gets executed? – Amir Gorji Jul 03 '20 at 09:01
  • 1
    @AmirGorji Exactly. It will be done either with a value provided as second param, or if you send an error in the first param of the callback it will throw the error and you can catch it with `try..catch` in the saga. – Martin Kadlec Jul 03 '20 at 09:16