当第三方javascript异步函数完成执行时,调用自定义函数

Call a custom function when a third party javascript async function completes its execution

本文关键字:执行 调用 自定义函数 第三方 javascript 异步 函数      更新时间:2023-09-26

我有一个场景,我希望在特定的第三方js函数完成执行后执行我的函数。

我不能编辑loadOne的源,但我可以添加/覆盖我的newLoadOne作为点击侦听器。因此,我可以代表它执行loadOne,并使用它返回的数据执行我的代码。

现在,我的newLoadOneloadOne方法的异步回调返回之前打印console.log

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();
});

这里是jsFiddle链接-注意:源代码中的$.ajax调用是为了解释loadOne有一些异步回调的方法。所以$(document).ajaxComplete不是答案。

您别无选择,只能轮询以查看异步方法是否已完成。据推测,它会以适当的频率改变一个对您可见的状态,您可以对其进行轮询(我们将该例程称为check_some_async_xhr_method_completed)。

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
    );
}

或者,如果你更喜欢使用承诺:

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;
}

或者,when库已经有一个处理轮询的例程。

在我看来这会起作用。。。

$(document).ajaxComplete(function (event, xhr, settings) {
  if ( settings.url === "the/url/that/loadone/uses" ) {
    // do your callback here
  }
});

对不起,只有当使用jQuery发出请求时,这才有效