问题
So I have tasks
object with ids and values. With for in loop I want to read 'members' property. If it exist, and first element of array !=='all'
I want to make request to firebase for read document by given id. But I cant use yield
, there is error:
Failed to compile.
./src/containers/modules/Tasks/store/sagas/tasksSagas.js
Line 27: Parsing error: Unexpected reserved word 'yield'
Why am I getting it? I can't use nested yields?
//Fetching users for tasks
for (const task in tasks) {
if (tasks[task].hasOwnProperty('members')) {
if (tasks[task].members[0]==='all'){
tasks[task].fetchedMembers = ['all']
}
else {
const fetchedMembers = tasks[task].members.map(member => {
const user = yield db.collection('users').doc(member).get()
const userData = user.data()
return {
uid: member,
...userData
}
})
tasks[task].fetchedMembers = fetchedMembers
}
}
}
回答1:
const fetchedMembers = tasks[task].members.map(member => {
const user = yield db.collection('users').doc(member).get()
const userData = user.data()
return {
uid: member,
...userData
}
})
The function you pass to .map
is not a generator function, so you can't use yield
in it. And it can't be a generator function, since map
knows nothing about generators or sagas.
One option is to create an array of promises, and then yield that (either wrapped in Promise.all, or redux-saga's all effect):
const promises = tasks[task].members.map(member => {
return db.collection('users').doc(member).get();
})
const members = yield all(promises);
const fetchedMembers = members.map(user => {
const userdata = user.data();
return {
uid: member,
...userData;
}
);
Another option is to write a mini-saga you want to do for each member, and then create an array of call effects, then yield all of those:
const callEffects = tasks[task].members.map(member => {
return call(function* () {
const user = yield db.collection('users').doc(member).get()
const userData = user.data()
return {
uid: member,
...userData
}
});
})
const fetchedMembers = yield all(callEffects);
来源:https://stackoverflow.com/questions/58207095/why-cant-i-use-nested-yield-in-for-in-loop-in-redux-saga