简体   繁体   English

当.then以正确的顺序执行时,如何使javascript函数起作用。

[英]How to make javascript functions work with .when .then toexecute in proper order

I've read many posts on this topic and think I should be using $.when and .then or .done for what I need, but not sure how to make it happen. 我已经阅读了许多有关此主题的文章,并认为我应该使用$ .when和.then或.done来满足我的需求,但不确定如何实现它。 Any help you can provide is appreciated. 您可以提供的任何帮助都将受到赞赏。

I have two functions that can run simultaneously, and a third function that can only run after the first two are complete. 我有两个可以同时运行的功能,以及第三个只能在前两个完成后才能运行的功能。 Here's a basic breakdown of what I'm doing. 这是我在做什么的基本分解。

function one() {
  //do lots of stuff to get variable values set
  return $.post("sess_push.php", {hotel:hotel, hlng:hLng, hlat:hLat})
            .done(function( data ) {
            console.log("Done in function one");
            alert( "Done in function one" );
        });
} //end function one

function two() {
  //do lots of stuff to get variable values set
  return $.post("sess_push.php", {metro:metro, lat:lat, lng:lng})
        .done(function( data ) {
        console.log("Done with function 2");
        alert ("Done with function 2");
    });
} //end function two

function three() {
    console.log("Starting function 3");
        alert("Starting function 3");
        $.post("itenerary.php", {})
        .done(function( data ) {
          $("#itenerary").html(data);
        });
} // end function three

How do I use promises and/or deferred to get these to execute in the order I need? 如何使用承诺和/或延期使它们按我需要的顺序执行?

I've tried to use the following $.when, but function three runs before the other two are done. 我试过使用以下$ .when,但是功能3在其他两个完成之前运行。 $.when(one(), two()).then( three, myFailure ); $ .when(one(),two())。then(three,myFailure);

I'm sure there are better ways to make this work, but this is what did the trick for me. 我敢肯定,有更好的方法可以完成这项工作,但这就是我的诀窍。 Thanks to Jaromanda X for providing the base for what I used to get it working. 感谢Jaromanda X为我用来使其工作提供了基础。 if others have ways to optimize this, I'm all for it. 如果其他人有优化的方法,我全力以赴。

function one() {
  var d = $.Deferred();
  //do lots of stuff to get variable values set

  $.post("sess_push.php", {hotel:hotel, hlng:hLng, hlat:hLat});
  console.log("Done in one");
  d.resolve();
  return d.promise();
} //end function one

function two() {
  var d = $.Deferred();
  //do lots of stuff to get variable values set

  $.post("sess_push.php", {metro:metro, lat:lat, lng:lng});
  console.log("Done with two");
  d.resolve();
  return d.promise();
} //end function two

function three() {
    var d = $.Deferred();
    $.post("itenerary.php", {})
    .done(function( data ) {
        $("#itenerary").html(data);
    console.log("Done in 3");
    });
    d.resolve();
    return d.promise();

} // end function three

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM