javascript - Setting variable to result of function acting very strange -
javascript - Setting variable to result of function acting very strange -
i have function in javascript supposed homecoming array of articles linked wikipedia page, given title.
here is:
function getlinksfrom(title, returnarray, plcontinue) { var url = 'http://en.wikipedia.org/w/api.php?action=query&prop=links&titles=' + title + '&format=json&pllimit=500&plnamespace=0&callback=?'; if (!returnarray) { returnarray = []; } if (!plcontinue) { plcontinue = ''; } if (returnarray.length === 0 || plcontinue !== '') { if (plcontinue !== '') { url = 'http://en.wikipedia.org/w/api.php?action=query&prop=links&titles=' + title + '&format=json&pllimit=500&plnamespace=0&plcontinue=' + plcontinue + '&callback=?'; } $.ajax({url: url, datatype: 'json', async: false, success: function(data) { (key in data['query']['pages']) { links = data['query']['pages'][key]['links']; } (var = 0; < links.length; += 1) { returnarray.push(links[i]['title']); } if (data.hasownproperty('query-continue')) { plcontinue = data['query-continue']['links']['plcontinue']; } else { plcontinue = ''; } console.log(returnarray); homecoming getlinksfrom(title, returnarray, plcontinue); } }); } console.log(returnarray); homecoming returnarray; }
when run function , watch console, console.log(returnarray); lines set want in console. arrays of strings. here's confused.
i want store returnarray, in variable called links. here's line, below function.
var links = getlinksfrom('united states');
but links doesn't end equalling wonderful thing logged before. instead, contains array of objects, isn't right length.
what's happening here?
since getlinksfrom
asynchronous function, when js evaluates function phone call writes result links
variable immediately. @ point of time returnarray
empty!
take @ picture:
it shows pushing returnarray
happens after assigning links
variable and, likely, after using variable.
so if utilize asynchronous code, cant't a = b()
. in case people utilize callbacks: b(function(a) { /* */ })
(argument kind of "success" function). should rewrite code work asynchronously using callbacks.
but there 1 more problem code: never stop self-calls. after every successfull request send , never stop. maybe, after several requests woun't usefull info anymore, why bother remote server , user's network useless requests? don't recursion when you're done. instead of can phone call callback
inform function caller you're done.
javascript jquery ajax api wikipedia
Comments
Post a Comment