简体   繁体   中英

Execute a function after N async calls in javascript/jQuery

I have 7 async functions calls after which I need to execute a function. Sample structure of code.

Code

<script>
(function(){

   f1();
   f2();
   f3();
   f4();
   f5();
   f6();
   f7();

   // execute final() when f1-f7 async function have executed. 
    //  All the function have ajax request
   final();

});
</script>

My Current Approach

<script>
    (function(){
       var finalExecuted = false;
       f1();
       f2();
       f3();
       f4();
       f5();
       f6();
       f7();

       // execute final() when f1-f7 async function have executed. 
        //  All the function have ajax request

      setInterval(function(){ 
       if($.active == 0 && !finalExecuted) {
         final();
         finalExecuted = true;
       } },500); 

       });
 </script>

Is this the correct approach to do? All the function f1-f7 are different functions and fetch different values from API's.

The approach you've used is good, A solid approach of working with asynchronous functions would be the following :

you are using ajax requests, if you are using JQuery to make your AJAX requests then you are working with promises, here is a solution you can use :

Create an array of promises

var myPromises = [f1(),f2(),f3(),f4(),f5(),f6(),f7()];

now that you have your array set up use Promise.all function

Promise.all(myPromises).then(function(vals){
    // write your code here
});

Promise.all gets invoked once all your async tasks passed in the array have finished executing.

If your functions return a promise, use them.

Using async/await :

(async function(){
       let res1 = await f1();
       let res2 = await f2();
       let res3 = await f3();
       ...

       if(res1 && res2 && res3 && ... && resN)
          final();
       });

Using Promise :

let promise1 = f1(); // some Promise in f1()
let promise2 = f2();
...
let promises = [promise1, promise2, ...];
Promise.all(promises).then((res) => final());

If not? Why don't you use it? create a Promise in onload or onreadystatechange then do like above. Or you can try fetch

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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