我正在尝试遍历/users 路径并将其加入我的 auth().listUsers 结果,但是这段代码:
https://github.com/QuantumInformation/svelte-fullstack-starter/blob/master/firebase_specific/functions/src/users.ts#L32
export async function getSomeUsers(amount: number) {
try {
const listUsersResult = await admin.auth().listUsers(amount)
const parsedUsers = listUsersResult.users.map(stripUserSensitiveInfo).map(async user => {
console.log("try read_______________" + user.uid)
let userProfileSnapshot = await admin
.database()
.ref("users/" + user.uid)
.once("value")
console.log("end try read_______________" + user.uid)
return { ...user, userProfileSnapshot }
})
return parsedUsers
} catch (error) {
console.error("Error listing users:", error)
throw new Error("Error users" + error)
}
}
给出这个错误
Converting circular structure to JSON at JSON.stringify () at stringify
但这段代码工作正常
export async function getSomeUsers(amount: number) {
try {
const listUsersResult = await admin.auth().listUsers(amount)
const parsedUsers = listUsersResult.users.map(stripUserSensitiveInfo).map( user => {
return 1
})
return parsedUsers
} catch (error) {
console.error("Error listing users:", error)
throw new Error("Error users" + error)
}
}
最佳答案
问题在于 map
中的嵌入式异步调用。运算符(operator)
为了使其工作,您需要等待每次迭代,这也是非常低效的。这是因为对于每个额外的查询,所花费的时间都会线性增加。
我的建议是以可扩展的方式转换整个逻辑。幸运的是,您的 listAllUsers()
就是这种情况。一次调用返回所有结果的函数
export async function getSomeUsers(amount: number) {
try {
/**
* fetch all the users with the provided limit
*/
const allUsers = await admin.auth().listUsers(amount)
/**
* loop through the returned values and create a promise to fetch
* Each of their document
*/
const listUsersResult = allUsers.users.map(user => {
return admin
.database()
.ref("users/" + user.uid)
.once("value")
})
/**
* When all the user documents have been fetched, iterare through them and deduce their values
*/
const parsedUsers = await Promise.all(listUsersResult).then(docSnashots => {
return docSnashots.map(snapshot => {
console.log("end try read_______________" + snapshot.val())
/**
* The records need to be matched with the original values
*/
const originalUserData = allUsers.users.find(u => u.uid === snapshot.key)
return { ...originalUserData, ...snapshot.val() }
})
})
return parsedUsers
} catch (error) {
console.error("Error listing users:", error)
throw new Error("Error users" + error)
}
}
注意 由于循环,此方法的计算密集度更高,但由于每个读取操作彼此独立,因此更省时。它可以在您确定读取操作总是需要很短的时间并且(也许)比循环的计算更节省资源的情况下进行修改
关于javascript - Firebase 简单查询给出错误 : "Converting circular structure to JSON at JSON.stringify",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60250221/