I have a scenario where I would like my function to be executed after a particular 3rd party js function completes its execution.
I can't edit the source of loadOne however I could add/override my newLoadOne as on click listener. So I can execute the loadOne on its behalf and execute my code with the data it returns.
Right now, my newLoadOne prints console.log before the loadOne method's async callback return.
HTML
<select id="option1">
<option>1</option>
<option>2</option>
<option>3</option>
</select>
<select id="option2">
<option>One</option>
<option>Two</option>
<option>Three</option>
</select>
<input id="submit" type="button" value="Submit" />
JavaScript
function loadOne(){
someAsyncXhrMethod(with_its_own_parameters);//its own xhr method with aync callbacks
}
function newLoadOne(){
(function(){loadOne(); console.log('done');}());
}
function optionschanged(){
console.log('options changed');
}
function bEvents(){
$('#option1').change(optionschanged);
$('#option2').change(optionschanged);
$('#submit').bind('click', newLoadOne); //this is where i replace the call to loadOne with my newLoadOne
}
$(document).ready(function () {
console.log('ready');
bEvents();
});
here is the jsFiddle link - Note: $.ajax call in the source is to explain the method loadOne has some async callbacks. So $(document).ajaxComplete is not the answer.
You have no real choice but to poll to see if the async method has completed. Presumably it does something that changes a state which is visible to you that you can poll for (we'll call that routine check_some_async_xhr_method_completed), at some appropriate frequency.
function newLoadOne () {
loadOne ();
check_completion (function (completed) {
console.log (completed ? 'done' : 'never finished');
});
}
function check_completion (callback) {
var number_of_tries = 20;
var timer = setInterval (
function () {
if (check_some_async_xhr_method_completed ()) {
clearInterval (timer);
callback (true);
} else if (!number_of_tries--) {
clearInterval (timer);
callback (false);
}
},
500
);
}
Or, if you would prefer to use promises:
function newLoadOne () {
loadOne ();
check_completion ().then (
function () {console.log ('done'),
function () {console.log ('never finished')
);
}
function check_completion () {
var promise = Promise.new();
var number_of_tries = 20;
var timer = setInterval (
function () {
if (check_some_async_xhr_method_completed ()) {
clearInterval (timer);
p.fulfill ();
} else if(!number_of_tries--) {
clearInterval (timer);
p.reject ();
}
},
500
);
return promise;
}
Or, the when library already has a routine which handles polling.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With