【发布时间】:2019-10-29 15:10:11
【问题描述】:
我试图根据年龄对从数据库返回的一组用户对象进行排序,但发生了一些非常奇怪的事情。
以下代码不起作用:
async function getAllUsers(){
let _users = await User.find({});
//error here, it shows that cannot read age of null, but why is
//stats undefined? I thought the async/await already resolved the promise?
let sorted = _users.sort((a, b) => b.stat.age - a.stat.age)
return sorted;
}
这是经过大量研究后的工作代码,但我不确定为什么会这样
async function getAllUsers(){
let _users = await User.find({});
let deepclone = JSON.parse(JSON.stringify(_users))
let sorted = deepclone.sort((a, b) => b.stat.age - a.stat.age)
return sorted;
}
我知道我正在从_users 创建一个全新的对象,因此deepclone 失去了对_users 数组对象的引用,但这对解决问题有何帮助?
//=======只是为了清楚=======//
let _users = await User.find({})
console.log(_users)
/* this logs
{
_id: 65a4d132asd,
stat: { age: 24 }
}
*/
//without doing JSON.parse & JSON.stringify
_users.sort((a,b) => {
console.log(a)//this logs ---> {_id: 65a4d132asd,stat: { age: 24 }}
console.log(a.stat)//this logs ---> undefined
})
//with JSON.parse & JSON.stringify
let deepclone = JSON.parse(JSON.stringify(_users))
deepclone.sort((a, b) => {
console.log(a)//this logs ---> {_id: 65a4d132asd,stat: { age: 24 }}
console.log(a.stat)//this logs ---> 24
})
【问题讨论】:
-
您是否尝试在排序前打印
_users?您是否已验证每个条目都有非nullstats属性? -
是的,我在控制台登录 _user 之后就获得了所有用户。我什至 console.log a 和 b 在排序函数的回调函数中,我可以看到所有内容。但是,在排序的回调中,一旦我登录(a.stats),它就会显示未定义。
-
我知道这并不能解决 JavaScript 的问题,但为什么不让数据库为你做排序呢?
-
您是否注意到您在
_user(单数)而不是_users(复数)上调用sort? -
抱歉,我发布问题时打错字了
标签: javascript async-await immutability