Skip to content Skip to sidebar Skip to footer

Setting Variable To Result Of Function Acting Very Strange

I have a function in javascript that is supposed to return an array of all the articles linked to by a wikipedia page, given the title. Here it is: function getLinksFrom(title, ret

Solution 1:

Since getLinksFrom is asynchronous function, when JS evaluates function call it writes result to the links variable immediately. But at that point of time returnArray is empty!

Take a look at the picture:

enter image description here

It shows that pushing to the returnArray happens after assigning it to the links variable and, most likely, after using this variable.

So if you use asynchronous code, you cant't just do a = b(). Usually in this case people use callbacks: b(function(a) { /* do something with a */ }) (argument is kind of a "success" function). So you should rewrite your code to work asynchronously using callbacks.

But there is one more problem with you code: you never stop self-calls. After every successfull request you send another and never stop. Maybe, after several requests you woun't get any usefull data anymore, so why bother remote server and user's network with useless requests? Just don't do recursion when you're done. Instead of that you can call callback to inform your function caller that you're done.

Post a Comment for "Setting Variable To Result Of Function Acting Very Strange"