Run function after another function completes JavaScript and JQuery -
Run function after another function completes JavaScript and JQuery -
i need little help. i'm trying run sec function "likelinks();" after first function "getlikeurls();" finished. because 2nd function relies on links array execute. seems trying run @ same time.
any help appreciated.
var links = []; var url = '/' + window.location.pathname.split('/')[1] + '/' + window.location.pathname.split('/')[2] + '/' getlikeurls(); likelinks(); function getlikeurls() { (i = 1; < parseint(document.getelementsbyclassname('pagenav')[0].getattribute('data-last')) + 2; i++) { var link = $.get(url + 'page-' + i, function(data) { //gets links current page $(data).find('a[class="likelink item command like"]').each(function() { links.push($(this).attr('href')); // puts links in array }); }); } } function likelinks() { (t = 0; t <= links.length; t++) { var token = document.getelementsbyname('_xftoken')[0].getattribute('value') $.post(links[t], { _xftoken: token, _xfnoredirect: 1, _xfresponsetype: 'json' }, function(data) {}); } }
the link
variables jquery deferred objects - store them in array , can utilize $.when()
create mew deferred object resolves when of previous $.get()
operations have completed:
function getlikeurls(url) { // nb: parameter, not global var defs = [], links = []; // nb: links no longer global (...) { var link = $.get(...); defs.push(link); } // wait previous `$.get` finish, , when have create new // deferred object homecoming entire array of links homecoming $.when.apply($, defs).then(function() { homecoming links; }); }
then, start chain of functions:
getlikeurls(url).then(likelinks);
note likelinks
passed array of links instead of accessing global state. function should rewritten allow wait $.post
calls complete, too:
function likelinks(links) { // loop invariant - take outside loop var token = document.getelementsbyname('_xftoken')[0].getattribute('value'); // create array of deferreds, 1 each link var defs = links.map(function(link) { homecoming $.post(link, { _xftoken: token, _xfnoredirect: 1, _xfresponsetype: 'json' }); }); // , when they're done homecoming $.when.apply($, defs); }
p.s. don't set (relatively) expensive parseint(document.getattribute(...))
look within for
statement - it'll cause evaluated every iteration. calculate 1 time outside loop , store in variable. there's few other places you're repeating calls unnecessarily, e.g. window.location.pathname.split()
javascript jquery function
Comments
Post a Comment