无法访问对象的属性,但是对象存在

时间:2019-06-15 04:28:05

标签: javascript async-await immutability

我试图根据用户的年龄对从数据库返回的一系列用户对象进行排序,但是确实发生了一些奇怪的事情。

以下代码不起作用:

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数组对象的引用,但这如何帮助解决问题? / p>

// =============== //

 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
   })

1 个答案:

答案 0 :(得分:0)

 // Maybe this line is not correct

 let _users = await User.find({});

 // Try to console _users 

// It's might be the _users was not return a correctly format data, then you use JSON.parse(JSON.stringify(_users)) to stringify the _users, so it works correctly