简体   繁体   English

Redux:在匿名函数中产生

[英]Redux: yield inside an anonymous function

So, i am entirely new to Reudx-Saga and i have been testing it a for a few days.所以,我对Reudx-Saga完全Reudx-Saga ,我已经对其进行了几天的测试。

I have a working understanding of generators, actions, redux-stores, sagas and others.我对生成器、动作、redux-stores、sagas 和其他东西有深入的了解。 Have some good experience with JS overall.总体上对 JS 有一些很好的经验。

I have a scenario where i have a function as follows:我有一个场景,我有一个功能如下:

project().itemClicked(val => /* do something with */)

Now, i am trying to put this code inside a generator function, in my saga .现在,我试图将此代码放在我的saga的生成器函数中。 I basically need to put an action, but for that, i need to use the yield keyword.基本上,我需要put一个动作,但对于这一点,我需要使用yield关键字。 I need to put the val returned by the callback using yield put .我需要使用yield put回调返回的val

I have to make a few other yield call(function..) calls after executing the above requirement.执行上述要求后,我必须进行一些其他的yield call(function..)调用。 I tried wrapping my function inside a Promise , but the problem with that is, the promise is only getting called only once intemClicked is fired and thus the rest of my yield calls are being blocked.我尝试将我的函数包装在Promise ,但问题是,只有在触发了intemClicked才会调用intemClicked ,因此我的其余yield调用被阻止。

Is there a way i can yield inside my anonymous function ?有没有办法yield我的匿名函数yield

Pardon my wording because i am still learning/understanding Redux-Saga .请原谅我的措辞,因为我仍在学习/理解Redux-Saga

The solutions depends on if the callback can be called multiple times or only once.解决方案取决于回调是可以被调用多次还是只调用一次。

If it is going to be called only once, you first approach - converting it to promise - was the right one, you just need to use fork to make the wait non-blocking.如果它只被调用一次,你的第一种方法 - 将它转换为 promise - 是正确的,你只需要使用fork使等待非阻塞。

function * itemClickedSaga() {
  const val = yield new Promise(resolve => {
    project().itemClicked(resolve)
  })
  yield put(someActionCreator(val))
}

function * someSaga() {
  // waits for the promise in different saga
  // using fork to not wait for the call bellow
  yield fork(itemClickedSaga) 
  yield call(somethingSomething)
}

In case the callback can be called multiple times, you might want to use an eventChannel :如果回调可以被多次调用,您可能需要使用eventChannel

function createItemClickedChannel = () => {
  return eventChannel(emitter => {
    project().itemClicked(emitter)
  })
}

function itemClickedSaga(val) {
  yield put(someActionCreator(val))
}

function * someSaga() {
  const itemClickedChannel = yield call(createItemClickedChannel)
  yield takeEvery(itemClickedChannel, itemClickedSaga) 
  yield call(somethingSomething)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM