如何使javascript函数与.when.then一起工作,以正确的顺序执行

如何使javascript函数与.when.then一起工作,以正确的顺序执行,javascript,jquery,Javascript,Jquery,我读过很多关于这个主题的帖子,认为我应该使用$.when和.then或.done来满足我的需要,但不确定如何实现。非常感谢您提供的任何帮助 我有两个可以同时运行的函数,第三个函数只能在前两个函数完成后运行。这是我所做工作的基本分类 function one() { //do lots of stuff to get variable values set return $.post("sess_push.php", {hotel:hotel, hlng:hLng, hlat:hLat})

我读过很多关于这个主题的帖子,认为我应该使用$.when和.then或.done来满足我的需要,但不确定如何实现。非常感谢您提供的任何帮助

我有两个可以同时运行的函数,第三个函数只能在前两个函数完成后运行。这是我所做工作的基本分类

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
我如何使用承诺和/或延期来按照我需要的顺序执行这些承诺

我尝试使用以下$.when,但函数在其他两个完成之前运行了三次。
$.when(1(),2())。然后(3,myFailure)

我确信有更好的方法来实现这一点,但这正是我成功的原因。感谢Jaromanda X为我过去的工作提供了基础。如果其他人有办法优化这个,我完全赞成

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

它应该如您所期望的那样工作-消除警报,这有帮助吗?请参阅-使用
$延迟
而不是
$。post
-但是承诺是承诺我发出了警报,但它仍然没有按所需的顺序执行。当它运行时,它几乎总是说“使用函数2完成”、“启动函数3”,然后是“使用函数1完成”。我将简化我的脚本,并尝试使基础正常工作。