Created
April 20, 2011 18:46
-
-
Save sintaxi/932292 to your computer and use it in GitHub Desktop.
example of how to make calls in parallel
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var http = require("http") | |
// expensive call | |
// takes 2 sec | |
function name(cb){ | |
setTimeout(function(){ cb("Brock") }, 2000) | |
} | |
// expensive call | |
// takes 2 sec | |
function place(cb){ | |
setTimeout(function(){ cb("Canada") }, 2000) | |
} | |
/* ------------------------------------ | |
Example 1 | |
- make calls sequentially | |
- takes 4 sec to complete | |
*/ | |
http.createServer(function(req, rsp){ | |
name(function(name){ | |
place(function(place){ | |
rsp.end(name + place) | |
}) | |
}) | |
}).listen(8001) | |
/* ------------------------------------ | |
Example 2a | |
- make calls in parallel | |
- takes 2 sec to complete | |
*/ | |
http.createServer(function(req, rsp){ | |
var counter = 2 | |
var results = {} | |
name(function(name){ | |
counter -- | |
results["name"] = name | |
if(counter == 0) | |
rsp.end(results["name"] + results["place"]) | |
}) | |
place(function(place){ | |
counter -- | |
results["place"] = place | |
if(counter == 0) | |
rsp.end(results["name"] + results["place"]) | |
}) | |
}).listen(8002) | |
/* ------------------------------------ | |
Example 2b | |
- make calls in parallel using generic helper | |
- takes 2 sec to complete | |
- http://stackoverflow.com/questions/4631774/coordinating-parallel-execution-in-node-js | |
*/ | |
function parallel(calls, cb){ | |
var counter = calls.length | |
var results = [] | |
function makeCb(index){ | |
return function(){ | |
counter -- | |
var result = [] | |
for (var i=0;i<arguments.length;i++) | |
result.push(arguments[i]) | |
results[index] = result | |
if(counter == 0) | |
cb(results) | |
} | |
} | |
for (var i=0;i<calls.length;i++) | |
calls[i](makeCb(i)) | |
} | |
http.createServer(function(req, rsp){ | |
parallel([name, place], function(results){ | |
rsp.end(results[0] + results[1]) | |
}) | |
}).listen(8003) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment