如何在使用AJAX时控制JavaScript函数的顺序

How to control the order of JavaScript functions while using AJAX

本文关键字:JavaScript 控制 函数 顺序 AJAX      更新时间:2023-09-26

我的设置

function ajaxLoadSth(value, attribute) {
    $.post( url, value, function(response) {
        // interpreting the response
        var foobar = $('#foo') + $('.bar').find('.sth');
        // print interpretation into DOM
        container.append(foobar);
        // do some funky stuff
        doSomeFooWithDom();
        checkSomeBarHere();
        updateSomeValuesThere();
        // now call the function again with different values 
        // THIS IS WHAT MY QUESTION REFERS TO **************
        if ( true ) {
            ajaxLoadSth(newValue, newAttribute);
        }
    });
}

我的问题

函数//做一些时髦的事情-部分,一些DOM操作完成执行之前,不能调用自己-,但它确实完成了

我的问题

  • 为什么?是因为那些"时髦的东西"位于外部功能中吗?当涉及到同步执行时,这重要吗
  • 我如何才能让"自己的调用"等到上面的东西完成

我已经考虑过通过设置全局变量触发处理程序来告知它们已经准备好的函数。每次触发处理程序时,函数都会检查是否所有变量都设置正确,然后执行函数调用。那呢?

非常感谢您提前抽出时间!

尝试回调例如

doSomeFunkyStuff(callback){
//DO SOME FUNKY
  callback();
}
function ajaxLoadSth(value, attribute) {
    $.post( url, value, function(response) {
        // interpreting the response
        var foobar = $('#foo') + $('.bar').find('.sth');
        // print interpretation into DOM
        container.append(foobar);
        // do some funky stuff
        doSomeFunkyStuff(function(){
           ajaxLoadSth(newValue, newAttribute);
        }
    });
}
  1. 功能是外部的这一事实并不重要。它们将同步执行:如果您使用DOM检查器并在这些函数中放置断点,您应该会发现它们将在AJaX调用调用之前按顺序执行。

  2. 我认为这里的关键是"等到上面的东西完成"——这些函数将按照您调用它们的顺序执行,但"完成"的结果可能是异步的。

我写了一个插件来处理这类东西,名为Pendant.js。其想法是,你想根据各种依赖关系推迟(一个或多个)给定函数的执行:dependency是一个传递给Pendant的函数,它会得到一个额外的参数resolve,这是一个在满足依赖关系时可以调用的函数。然后,您将递归调用作为dependant传递,该调用只有在Pendant的所有依赖项都已解析时才会执行。

jQuery还实现了开箱即用的"Promises",这正是我想要的,但使用了一种适合XHR的语言,我对此感到不舒服。话虽如此,它可能要健壮得多(并且有充分的文档记录!),所以你可能应该看看。