How to get value of property in javascript object? - javascript

I have an object which has status property. But I can't get the value of this property. Here is my code sample:
console.log("Resource.query()");
console.log(Resource.query());
console.log("Resource.query().status");
console.log(Resource.query().status);
Here is Chrome console:
As you see Resource.query().status returns undefined while Resource.query() returns the object. My question is how can I get the value of status ?
Thanks in advance.

query() is run asynchronously as noted in the tutorial (emphasis added):
$scope.phones = Phone.query();
This is a simple statement that we want to query for all phones. An important thing to notice in the code above is that we don't pass any callback functions when invoking methods of our Phone service. Although it looks as if the result were returned synchronously, that is not the case at all. What is returned synchronously is a "future" — an object, which will be filled with data when the XHR response returns. Because of the data-binding in Angular, we can use this future and bind it to our template. Then, when the data arrives, the view will automatically update.

try this:
Resource.query()[0].status

Related

Outlook Add-in argument exception on body.getAsync() method

According to https://dev.outlook.com/reference/add-ins/Body.html:
The GetAsync() method takes in 3 parameters. The first one is the Coercion Type which according to their documentation is a string value. The other two parameters for GetAsync are options and callback which are optional.
My code: var body = item.body.getAsync("html");
which gives this exception:
Exception details: outlook-web-16.00.js:formatted:5873 Uncaught Error: Sys.ArgumentTypeException: Object cannot be converted to the required type.
Am I not using the getAsync() method correctly? Most of the example code I've found online are using the callback parameter as well but if the options and callback parameters are optional and I only really need to get the contents of the email body as html, shouldn't this work?
P.S. This isn't an API versioning issue. I am definitely on 1.3 and body.getAsync does not return undefined.
Am I not using the getAsync() method correctly? Most of the example code I've found online are using the callback parameter as well but if the options and callback parameters are optional and I only really need to get the contents of the email body as html, shouldn't this work?
Since this method is a asynchronous, to get the result we have to use the callback. This sample should work:
Office.context.mailbox.item.body.getAsync("html", processHtmlBody);
function processHtmlBody(asyncResult) {
console.log(asyncResult.value)
}
This is a thread discussing getting the return value from asynchronous function using JavaScript.

How to understand asynchronous Meteor.call on the client side

I'm working on a Meteor project and want to get the return value of Meteor.call in template helpers on client side. At very first, I just set a variable in the call back function and get the variable's value outside the Meteor.call. I found out the code after Meteor.call doesn't execute at all. Then I searched a bit and use Session, it works. But I don't really understand the reason. Here's my original code and modified code. Can anyone explain a bit for me? Thanks!!
Original wrong code: html
<div id="text-result-main">
<h2>{{title}}</h2>
</div>
js
Template.texts.helpers({
title: function(){
var index = Router.current().params.index;
Meteor.call('getTitle', index,function(error, result){
titles = result;
});
console.log(titles);
return titles;
}});
Collection text.js
Text = new Mongo.Collection("text");
Meteor.methods({
'getTitle': function(myindex){
return Text.findOne({index: myindex}).title;
}});
The working code: js
Template.texts.helpers({
title: function(){
var index = Router.current().params.index;
Meteor.call('getTitle', index,function(error, result){
Session.set("titles",result);
});
console.log(Session.get("titles"));
return Session.get("titles");
}});
Notice that I didn't publish Collection Text to the client at all because it's just so huge. Every time when I refresh the page when running the wrong code, I can't see the content of "title" or see it on the console. But when I set the session, it works. I don't really understand how it works here. Thanks
There is two issues Asynchronicity and Reactivity
This affectation
Meteor.call('getTitle', index,function(error, result){
titles = result;
});
inside the meteor call is executed but in a asynch way. So the return of your helper is immediately called, and return a empty value.
Try it out in the console of your browser.
But then, why your template render correctly with {{title}} when you use a Session Variable ?
It's because the Session is a reactive data source, witch means that every change to it trigger a re-computation of all templates involving this piece of data.
Here is a timeline:
Methods is called
Return empty value
Method is executed, setting variable value
If the Variable is a reactive data source, template is re-computed. ( in your case, the session is a reactive data source. )
To go further
I would use a reactive var in that case, it's very close from a session variable, but the scope is limited to a template.
A good read on Reactive data source: http://richsilv.github.io/meteor/meteor-reactive-data-types/
The problem is the fact that Meteor.call() is asynchronous when paired with a callback.
So when title() starts executing, it does not wait for your Meteor.call() invocation to return a result (or possibly an error). It continues execution. This is called asynchronous execution.
In short, you are trying to log the value for the key titles which doesn't exist in Session (since the state of your asynchronous Meteor call is unknown, at this point of time).
Try moving the console log statement into the callback paired with your Meteor.call() and you can see the result once it has successfully been set in Session.
A workaround to your problem is to make your Meteor.call() synchronous like this:
Template.texts.helpers({
title: function(){
var index = Router.current().params.index;
var result = Meteor.call('getTitle', index); // <--- this is synchronous code now
Session.set("titles",result);
console.log(Session.get("titles"));
return Session.get("titles");
}});
Removing the callback makes Meteor.call() behave synchronously.
If you do not pass a callback on the server, the method invocation
will block until the method is complete. It will eventually return the
return value of the method, or it will throw an exception if the
method threw an exception.
(from http://docs.meteor.com/api/methods.html#Meteor-call)
Why not use something like this:
title: function(){
var index = Router.current().params.index;
var a = Text.findOne({index: myindex}).title;
console.log(a);
return a;
without methods

How does it make sense to use the variable name used to name a function inside that same function?

In this snippet, from the Angular documentation on $resource, the name of the function is user and inside the function they are using a variable of the same name.
var User = $resource('/user/:userId', {userId:'#id'});
var user = User.get({userId:123}, function() {
user.abc = true;
user.$save();
});
How does that make sense? And what are the rules around this?
When you call User.get(), it returns a promise, and processing continues. When that promise resolves, angular sets the variable you set it to, in this case user, to the value of the resolution. It also calls the success callback function, so you can safely change it at that point.
To use the above example, here is what happens.
you call `User.get({userId:123})
User.get returns a promise and sets var user to that promise
processing continues
the promise resolves, let's say to {id:123,name:"Imray"}
angular sets the variable user to {id:123,name:"Imray"}
angular calls your success callback, in which you:
set user.abc to true, so your object now is {id:123,name:"Imray",abc:true}
you call user.$save(), which saves it to the server, etc.
Essentially, there is nothing wrong with it, just be aware of the order of execution.
"user" is not name of function, its name of object which is read from given resource.
To be correct. User become proxy which is filled with data when http request is done.
Second parameter - function is callback which is called after user is successfully loaded, so user become fully created object.
So when .get is called it works exactly like that:
create variable user with "proxy"
read user from /user/123
actualize user varible with data and "resource's methods" ($save, $delete...)
call given function callback in which:
set abc in user object
save it back to the resource ($save introduces POST to /user/123
In documentation you can read: https://docs.angularjs.org/api/ngResource/service/$resource -
(part Usage/Returns)
"It is important to realize that invoking a $resource object method
immediately returns an empty reference (object or array depending on
isArray). Once the data is returned from the server the existing
reference is populated with the actual data. This is a useful trick
since usually the resource is assigned to a model which is then
rendered by the view. Having an empty object results in no rendering,
once the data arrives from the server then the object is populated
with the data and the view automatically re-renders itself showing the
new data. This means that in most cases one never has to write a
callback function for the action methods."
"user" doesnt have to be passed as parameter because user is set before callback is called.

Angular using fetched data outside function scope?

I'm returning a JSON object via a $http.get. I'm able to get the result set, and it's an array, but when I try to access the object outside the fetch() I'm getting undefined. Not sure what I'm missing, in order to do this, any help is appreciated.
Thanks Jimi.
myObject.fetch().then(function(myData) {
$scope.myData = myData;
});
console.log($scope.myData)
Your $scope.myData is undefined until fetch() finishes execution and calls the passed callback function.
in your example, console.log() is being called before the completion of myObject.fetch()
In the following example, it will most probably work (don't do it!)
setTimeout(function(){
console.log($scope.myData)
}, 2000);
I'm not telling you to do it this way, actually its a very bad way. best practice is to use that scope variable within the callback function only, since that where its actually set.

JSONP function call issue

i set up a webservice thats cross domain and needs to be contacted via json with padding
on a simple jquery codeline like this, i am successfull getting back json data.
$.getJSON("http://server/series/hist?jsonp=?", function(data){
console.log(data);
});
the webservice, will wrap the result in a function, whenever "jsonp" exists within in the url.
for those cases i used a default function name like:
myfunction({"a":1})
jquery helps me out here, and trys to call the function, that isnt existing ("myfunction()"). what i am trying to achieve instead is a simple call of the callback function (see above), to handle the data locally.
can you point me in the right direction?
thank you
I'm not quite sure what your problem actually is, but:
Interpretation 1
Assuming that by "locally" you mean "without using a callback":
That is impossible. JSON-P cannot work synchronously as it depends on the addition of a <script> element (which won't be processed until the current function has finished executing).
Interpretation 2
Assuming that by that isnt existing ("myfunction()") you mean "Your webservice always uses the function name myfunction:
Fix the webservice. jsonp=? means "Randomly generate a function name and pass it as the jsonp parameter.
The webservice must use that parameter to determine the function name used, and not use a fixed value such as myfunction.
Interpretation 3
You don't want to use JSON-P as the input, but to call your anonymous function directly.
You can't. It isn't stored anywhere you can access it. You have to rewrite your code so it isn't passed directly to getJSON:
function myFunction(data){
console.log(data);
}
$.getJSON("http://server/series/hist?jsonp=?", myfunction);
myfunction({"a":1})

Categories