问题
I'm all the time learning. My question is: why this:
let user = {
firstname: '',
secondname: ''
}
let hz = new Horizon({host: "164.132.192.28:3100"});
let table = hz('users');
hz.connect();
table.find(1).fetch().subscribe((value) => {
user = {
firstname: value.firstname,
secondname: value.secondname
}
//OR:
user.firstname = value.firstname;
user.secondname = value.secondname;
});
console.log(user);
gives me this:
And why I can't get value?:
console.log(user.firstname);
//prints nothing
My third question: how to just save the results from query into an object and use it outside the query? If I use 'return' keyword then results are similar. I know it's a newbie question but I'm really struggling with this... Can someone help me?
回答1:
The following line:
table.find(1).fetch().subscribe(...);
is calling asynchronous method. This means that provided callback will be called sometime later and not immediately at the moment when subscribe
is called. Therefore when it comes to console.log()
the browser prints out its string representation and at that moment both first and last name are have not yet being populated - thus empty fields. When later you click on the object to see its content in console - browser evaluates it at that moment and most likely the subscribe method has already finished - so you get your first and last name present.
Your code is actually saves data in the local user
variable. The thing you must remember is that you should access it only after subscribe
callback has been called.
来源:https://stackoverflow.com/questions/39151752/typescript-javascript-objects