[JS Newbie] Having a hard time understanding a variable assignment issue
ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
Get a virtual cloud desktop with the Linux distro that you want in less than five minutes with Shells! With over 10 pre-installed distros to choose from, the worry-free installation life is here! Whether you are a digital nomad or just looking for flexibility, Shells can put your Linux machine on the device that you want to use.
Exclusive for LQ members, get up to 45% off per month. Click here for more info.
[JS Newbie] Having a hard time understanding a variable assignment issue
Hello all,
I have a feeling this is a super simple issue but I can't seem to figure out how to resolve it. I am attempting to write a JS method (using CoffeeScript) that calls data from a public API. I am able to retrieve the data but I am not able to assign it to a variable outside of the method for use.
In summary of my issue: after calling getWeather(city), this.city is still set to undefined
Any help would be greatly appreciated:
Here is the current code I am working with:
CoffeeScript:
I'm not sure I understand completely, and don't know CoffeeScript. But the success and error callbacks that are sent to the ajax call shouldn't return anything. If they do, the return value is not assigned to anything. Also, ajax calls are asyncronous by default. That means the getWeather function returns first, the success or error functions are called later when the client get response from the server.
If you add "async:false" to the ajax call parameters, it doesn't return until you get data from the server. Then you can assign the result to a variable that you define in the getWeather function. And this variable you can return. But it's not a good solution. Nothing else can happen until you get response from the server, and that can take a long time. A better solution is simply to do whatever you need to do inside the success function.
I was under the impression that .done() waits for $.ajax() to finish before executing its line of code. The .done() method associates with the promise.success() method and the .fail() method associates with the promise.error() method.
Maybe its time to scrap this code and start over and see what I am misunderstanding
I am not all that familiar with js and only have learned a little coffee scripting (from rails), but even without any real understanding the script looks flawed.
If you look at the generated code, you set 'this.city' at the start, but the next time it 'looks' like it is getting set is inside a return value of a function. Thinking of most normal scopes,
if you are setting the value inside a function as a return value then it is never actually being assigned to your outer scope copy of the value.
Another weird part is in the empty function where you pass in 'result', you actually set your value and the returned item to the passed in item ... this also seems a little counter intuitive.
The above may be all wrong but it is just what it looks like to me
I am planning to dig deeper into why I had to do it this way but my first guess would be that I am not understand stopes well so I should brush up on that.
refers to the context of innermost anonymous function, not the context of its (grand-)parent function (where this.city variable was set). If you want to access parent context you either save it into a variable (like you did in your last post):
or set the context of the inner function explicitly using bind (you'll have to do this twice because you have two-level function nesting). Most return statements in your code can be removed.
Anyway, the problem with such code is that you never know if the variable have meaningful value or not. If your code depend on correct value of the variable, you should either use callbacks (say, put your logic directly into success callback of ajax) or use promises. I will not try to review your code from the promise point of view, because the way you use them seems pointless to me -- just set the variable in success callback. Btw, I've heard jQuery promises are flawed, so avoid them if you can I prefer Q for promises, but there are lots of alternatives available. Nevertheless Q's documentation is a good starting point to learn about promises.
When coding asyncronous stuff, hiding the complicated stuff in functions can just make problems. And it's not at all easier to read or understand. I think something like this is more clear:
Code:
<input type="text" id="city">
<script>
$("#city").on("change",function() {
$.ajax({
url: "http://api.openweathermap.org/data/2.5/weather",
dataType: 'json',
data: {
q: $("#city").val(),
APPID: "someAPIkey"
},
success: function(result) {
// update the weather on the page. Put some text in a div or something?
// you could add a function to parse and format the result, but why not put that code here?
},
error: function() {
// display some error message or maybe do nothing?
}
});
});
</script>
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.