javascript - Nested Callback stuck in Loop -
i have nested callback setup following:
function submitform() { buildcontent($('#content').val(), '', true, submitform) performsubmit(); } function buildcontent(textwithurl, textsource, issubmit, callback) { console.log("getwebcontent in progress"); getwebcontent(sendurls, buildcontent) console.log("getwebcontent done"); callback(); } function getwebcontent(content, callback) { $.ajax({.... sucess:function(msg) { ..... callback(); }
}
expected outcome when submitform called calls build conetent calls getwebcontent. o*nly after ajax call in inside getwebcontent sucessfull performsubmit(); executed.* reason loops , js hangs , becomes unresponsive , buildcontent console logs keeps prininting in loop.
it looks have misunderstanding of how callbacks work. when callback returns, not resume execution left off. function calling callback finishes immediately.
you need structure code so:
function submitform(){ buildcontent($('#content').val(), '', true, performsubmit); } function buildcontent(textwithurl, textsource, issubmit, callback){ console.log("getwebcontent in progress"); getwebcontent(sendurls, callback); } function getwebcontent(content,callback){ $.ajax({... success:function(msg){ .... console.log("getwebcontent done"); callback(); <-- performsubmit being called here, after of asynchronous work done } }); }
you'll notice pass performsubmit along callback each of these functions, , call in success function.
anything after getwebcontent call within buildcontent execute immediately, can't expect second call console.log after ajax request finished.
Comments
Post a Comment