How to use yield inside map for React Native

余生长醉 提交于 2020-01-15 07:46:29

问题


My goal is to execute the forked function inside map.

Here's what I've tried:

  function* doSomethingWithItem(item) {}

  yield all(items.map(item => {
    // ... some item checking
    return fork(doSomethingWithItem, item);
  }));

Tried also using yield fork() but got an error "yield is a reserved word..."

doSomethingWithItem() isn't called.

Appreciate the help.


回答1:


Since map uses lambda functions, you can't actually yield something from there directly.

yield all is a correct approach, but instead of fork, call effect looks more appropriate in this case because it is blocking, and, therefore, preserves the items processing order (if this matters):

function * doSomethingWithItem ( item ) {
  console.log('doSomethingWithItem', item)
}

function * doSomethingWithAllItems ( items ) {
  console.log('doSomethingWithAllItems')
  yield all(items.map(item =>
    call(doSomethingWithItem, item),
  ))
  console.log('done doSomethingWithAllItems')
}

function * mySaga () {
  yield call(doSomethingWithAllItems, [1, 2, 3, 4, 5])
}

I also checked your code, and doSomethingWithItem does work in my environment. Try wrapping your code in try/catch, maybe you have an error that makes saga stop.



来源:https://stackoverflow.com/questions/54193476/how-to-use-yield-inside-map-for-react-native

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!