所以我有带有ID和值的tasks
对象。使用for in循环,我想读取'members'属性。如果存在,并且是数组!=='all'
的第一个元素,我想通过给定的ID向firebase请求读取文档。但是我不能使用yield
,有错误:
Failed to compile.
./src/containers/modules/Tasks/store/sagas/tasksSagas.js
Line 27: Parsing error: Unexpected reserved word 'yield'
我为什么得到它?我不能使用嵌套收益吗?
//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
}
}
}
const fetchedMembers = tasks[task].members.map(member => {
const user = yield db.collection('users').doc(member).get()
const userData = user.data()
return {
uid: member,
...userData
}
})
您传递给.map
的函数不是生成器函数,因此不能在其中使用yield
。而且它不能成为生成器函数,因为map
对生成器或sagas一无所知。
[一种选择是创建一个Promise数组,然后产生它(包装在Promise.all中,或redux-saga的all效果):
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;
}
);
另一个选择是为每个成员编写一个迷你传奇,然后创建一系列调用效果,然后产生所有这些效果:
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);