Skip to content

Instantly share code, notes, and snippets.

@honzasterba
Created June 13, 2012 09:01
Show Gist options
  • Save honzasterba/2922931 to your computer and use it in GitHub Desktop.
Save honzasterba/2922931 to your computer and use it in GitHub Desktop.
ParallelRequests
/*
This is just an exploration of idea. I don't think this solution is elegant
enough. I'm looking for something that would work without the add() and done()
methods. Something like this:
new ParallelRequests(arrayOfRequests, callbackOnFinished);
The main idea is to work around delays when I need to aggregate data from
various sources before I can do something with them. Chaining is clearly not
the right way to go.
CHAINED REQUESTS
#1 |-----|
#2 |-----|
#3 |-----|
|<-- finally done!
PARELLEL REQUESTS
#1 |-----|
#2 |-----|
#3 |-----|
|<-- done already?
*/
function ParallelRequests(callback) {
this.callback = callback || function () {};
this.requests = [];
}
ParallelRequests.prototype = {
add: function (request) {
if (!request) { return; }
var wrapped = this._wrap(request);
this.requests.push(wrapped);
},
_wrap: function(request) {
var queue = this;
return function () {
try {
request();
} finally {
queue.done();
}
};
},
done: function () {
if (this.requests.length == 0) {
this.callback();
}
},
start: function () {
// ignore further modifications to requests
var reqs = this.requests.slice(0);
var request;
while (request = reqs.pop()) {
request();
}
}
}
var myBatchOfRequests = new ParallelRequests(function () {
console.log('all requests finished correctly');
});
// just a sample function supporting callback
function generateRandomNumber(name) {
var randomNumber = Math.round(Math.random() * 1000);
console.log(name + ' generated ' + randomNumber);
}
myBatchOfRequests.add(function () {
generateRandomNumber("1");
});
myBatchOfRequests.add(function () {
generateRandomNumber("2");
});
myBatchOfRequests.add(function () {
generateRandomNumber("3");
});
myBatchOfRequests.add(function () {
generateRandomNumber("4");
});
myBatchOfRequests.add(function () {
generateRandomNumber("5");
});
myBatchOfRequests.start();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment