在javascript中同步两个进程

时间:2014-05-08 12:06:00

标签: javascript jquery ajax

我的问题是我有两个不同的函数在其中运行ajax调用,这使它们异步。当两者都完成时我必须触发第三个功能。问题是异性,我知道他们两个都结束了。有解决方案,如:

  1. 让它们同步
  2. 让其中一个成功,
  3. 但是这两者都会导致延迟,因为这些ajax调用会带来大数据,所以最好让它们异步。

    有人可以建议我采取更清洁的方式。

    function f1(){
    //AJAX call}
    
    function f2(){
    //ajax call}
    
    when f1 and f2 are done fire f3().
    

3 个答案:

答案 0 :(得分:1)

我认为您正在寻找的是jQuery.done():https://api.jquery.com/deferred.done/

示例:

// 3 functions to call when the Deferred object is resolved
function fn1() {
$( "p" ).append( " 1 " );
}
function fn2() {
$( "p" ).append( " 2 " );
}
function fn3( n ) {
$( "p" ).append( n + " 3 " + n );
}
// Create a deferred object
var dfd = $.Deferred();
// Add handlers to be called when dfd is resolved
dfd
// .done() can take any number of functions or arrays of functions
.done( [ fn1, fn2 ], fn3, [ fn2, fn1 ] )
// We can chain done methods, too
.done(function( n ) {
$( "p" ).append( n + " we're done." );
});
// Resolve the Deferred object when the button is clicked
$( "button" ).on( "click", function() {
dfd.resolve( "and" );
});

答案 1 :(得分:1)

$.when( f1(), f2() ).done(function( a1, a2 ) {
  // a1 and a2 are arguments resolved for the f1() and f2() ajax requests, respectively.

});

答案 2 :(得分:1)

var async1 = $.get('hello.php');
var async2 = $.get('world.php');

$.when(async1, async2).done(function(hello, world) {
    // this function will be called only if async1 and async2 are resolved
    console.log(hello);
    console.log(world);
});

https://api.jquery.com/jQuery.when/