Created
February 16, 2011 04:38
-
-
Save marcello3d/828878 to your computer and use it in GitHub Desktop.
This file contains 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 waiter = new Waiter | |
var onlineUsers = waiter(function(done) { // done takes two arguments: (error, value) | |
// ... blah blah blah ... | |
done(err,value) | |
// ... blah ... | |
} | |
var latestPosts = waiter(function(done) { | |
// ... blah ... | |
// many async functions will accept 'done' as is | |
// ... | |
} | |
waiter.waitForAll(function(errors) { | |
if (errors) { // an array of all errors | |
// onlineUsers.error latestPosts.error have errors | |
} | |
// onlineUsers.value and latestPosts.value have values | |
}) | |
waiter.waitFor(1, function(errors) { ... }) // waits for a single result | |
waiter.waitForAll(function(errors) { ... }, 2000) // optional timeout (sets errors for any requests that don't respond in time) | |
waiter.waitFor(2, function(errors) { ... }, 2000) // count and timeout | |
// Oh and here's the code for waiter: | |
module.exports = function() { | |
var errors, | |
values = {}, | |
expecting = [], | |
count = 0, | |
max = 0, | |
waitCount, | |
waitCallback, | |
timeouter | |
function completed(result, error, value) { | |
result.error = error | |
result.value = value | |
expecting = expecting.filter(function(o) { return o !== result }) | |
if (error) { | |
(errors||(errors=[])).push(error) | |
} | |
count++ | |
if (waitCount == count) { | |
waitCallback(errors) | |
if (timeouter) { | |
clearTimeout(timeouter) | |
timeouter = null | |
} | |
} | |
} | |
function WaiterInstance(callback) { | |
max++ | |
var result = {} | |
expecting.push(result) | |
callback(function (error, value) { | |
completed(result,error,value) | |
}) | |
return result | |
} | |
WaiterInstance.waitFor = function(n, callback, timeout) { | |
if (count >= n) { | |
callback(errors,values) | |
} else { | |
waitCount = n | |
waitCallback = callback | |
if (timeout) { | |
timeouter = setTimeout(function() { | |
var error = new Error("Timeout after "+timeout+" ms") | |
expecting.forEach(function (result) { | |
completed(result, error) | |
}) | |
}, timeout) | |
} | |
} | |
return this | |
} | |
WaiterInstance.waitForAll = function(callback, timeout) { | |
return this.waitFor(max, callback, timeout) | |
} | |
return WaiterInstance | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment