Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to sync between two functions

Tags:

javascript

I have two functions that I want to call to third function when the other functions( one and two ) will be finished. I need that the first function and the second function will be called Asynchronous. for example

  var func1 = function( do something..... return arr )
  var func2 = function ( do something ..... return arr2 )

   if ( arr.length > 0  && arr2.length > 0 )
       var func3 = function( do something )

my qeustions:

  1. what is the best way to do it ?

  2. How I call to function in Asynchronous way ?

like image 652
user1365697 Avatar asked Sep 26 '26 21:09

user1365697


1 Answers

If you have jQuery, you could use their Deferred objects:

var func1 = function () {
    var dfd = $.Deferred();

    setTimeout(function () {
        // do your processing
        dfd.resolve(arr1);
    }, 0);

    return dfd.promise();
};
var func2 = function () {
    var dfd = $.Deferred();

    setTimeout(function () {
        // do your processing
        dfd.resolve(arr2);
    }, 0);

    return dfd.promise();
};

$.when(func1(), func2()).then(function (arr1, arr2) {
    if ( arr.length > 0  && arr2.length > 0 ) {
        func3();
    }
});

Related questions:

  • How can jQuery deferred be used?
  • How can I create an Asynchronous function in Javascript?
like image 180
jbabey Avatar answered Sep 29 '26 10:09

jbabey