我有包含用户 ID 的对象数组。
const userIDs= [{key: 'user_1'},{key: 'user_2'}, {key: 'user_3'}];
我想用 cloud firestore 中的用户数据填充它。
const userIDs= [
{key: 'user_1', name: 'name1'},
{key: 'user_2', name: 'name2'},
{key: 'user_3', name: 'name3'}
];
最快、最便宜的方法是什么?
这是我目前的做法。
const filledUsers = [];
for (let index in userIDs) {
const user = Object.assign({}, concatUsers[index]);
const snapshot = await usersRef.doc(user.key).get();
filledUsers.push(Object.assign(user, snapshot.data()));
})
Use await
for循环内部效率低下。相反,最好使用Promise.all
在被处决名单上ref.get()
进而await
.
如果需要降低价格,就需要应用缓存。
请参阅下面的源代码。
// module 'db/users.js'
const usersRef = db.collection('users');
export const getUsers = async (ids = []) => {
let users = {};
try {
users = (await Promise.all(ids.map(id => usersRef.doc(id).get())))
.filter(doc => doc.exists)
.map(doc => ({ [doc.id]: doc.data() }))
.reduce((acc, val) => ({ ...acc, ...val }), {});
} catch (error) {
console.log(`received an error in getUsers method in module \`db/users\`:`, error);
return {};
}
return users;
}
// Usage:
//
// (await getUsers(['user_1', 'user_2', 'user_3']))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)