Patrick1870 Patrick1870 -4 years ago 227
TypeScript Question

Typescript/Javascript objects

I'm all the time learning. My question is: why this:

let user = {
firstname: '',
secondname: ''

let hz = new Horizon({host: ""});
let table = hz('users');
table.find(1).fetch().subscribe((value) => {
user = {
firstname: value.firstname,
secondname: value.secondname

user.firstname = value.firstname;
user.secondname = value.secondname;



gives me this:


And why I can't get value?:

//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?

Answer Source

The following line:


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download