Skip to content

Instantly share code, notes, and snippets.

@gs-akhan
Last active August 29, 2015 14:05
Show Gist options
  • Save gs-akhan/4a7fcea1c0e5a3d09697 to your computer and use it in GitHub Desktop.
Save gs-akhan/4a7fcea1c0e5a3d09697 to your computer and use it in GitHub Desktop.
Simple Async handling
var uselessAsync = {};
uselessAsync.parallel = function(tasks, callback) {
var completed = 0;
var finalData = [];
var cb = function(err, data, iter) {
completed++;
finalData[iter] = data;
if(completed === tasks.length) {
callback(finalData);
}
};
//Loop through the tasks and exceute them by passing in callback which excutes and checks
//for the counter variable if equal to number of tasks then it assumes it to be last
//task and then executes the main callback the user gives.
for(var i = 0 ; i < tasks.length; i++) {
tasks[i]((function(ii) {
return function(err, data) {
cb(null, data, ii);
};
}(i)));
}
};
@gs-akhan
Copy link
Author

gs-akhan commented Sep 1, 2014

How to use

uselessAsync.parallel([
        function(cb) {
            setTimeout(function() {

                cb(null,'one');
            }, 3000);
        },
        function(cb) {
            setTimeout(function() {
                cb(null,'Two');
            }, 1000);
        },
        function(cb) {
            setTimeout(function() {
                cb(null,'Three');
            }, 5000);
        } 

        ], function(data) {
            console.log(data);
                        //Outputs as ['one', 'two', 'three']
        });

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment