WinchenzoMagnifico
WinchenzoMagnifico

Reputation: 3415

How to run a function after two async functions complete

Say I have an array of functions that invoke a setTimeout.

[
  function(cb){
    setTimeout(function(){
      cb('one');
    }, 200);
  },
  function(cb){
    setTimeout(function(){
      cb('two');
    }, 100);
  }
]

Is there a way to access the time parameter (200, 100) and save the sum of that to a variable?

I want to execute a function only when both of those functions are done

Upvotes: 2

Views: 1078

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386560

You can mimic it with a closure for the count.

function out(s) {
    var node = document.createElement('div');
    node.innerHTML = s + '<br>';
    document.getElementById('out').appendChild(node);
}

var f = [
        function (cb) { setTimeout(function () { cb('one'); }, 100); },
        function (cb) { setTimeout(function () { cb('two'); }, 200); }
    ],
    useCounter = function () {
        var count = 2;
        return function (s) {
            count--;
            out(s + ' ' + count);
            !count && out('done');
        }
    }();

f[0](useCounter);
f[1](useCounter);
<div id="out"></div>

Upvotes: 0

Steve Greatrex
Steve Greatrex

Reputation: 15999

A better approach is to use promises and Promise.all:

var task1 = new Promise(function(resolve,reject) {
    setTimeout(function() {
        //do something
        resolve();
    }, 100);
});

var task2 = new Promise(function(resolve,reject) {
    setTimeout(function() {
        //do something
        resolve();
    }, 200);
});

Promise.all([task1, task2]).then(function() {
    //will be executed when both complete
});

Upvotes: 2

Related Questions