问题
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