用javascript同步两个进程

synchronizing two process in javascript

本文关键字:两个 进程 javascript 同步      更新时间:2023-09-26

我的问题是我有两个不同的函数在运行,其中有ajax调用,这使它们异步。当两者都完成时,我必须启动第三个函数。问题是异步性质,我可以知道它们何时结束。有这样的解决方案:

  1. 使它们同步
  2. 把一个人置于另一个人的成功之中

但这两者都会导致延迟,因为这些ajax调用带来了大数据,所以最好让它们异步。

有人能给我推荐一种更清洁的方法吗。

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

我认为您正在寻找的是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" );
});
$.when( f1(), f2() ).done(function( a1, a2 ) {
  // a1 and a2 are arguments resolved for the f1() and f2() ajax requests, respectively.
});
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/