Last active
August 29, 2015 14:00
-
-
Save bjouhier/11234661 to your computer and use it in GitHub Desktop.
waitForOne.js
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 galaxy = require('galaxy'); | |
function *waitForOne(futures) { | |
return yield galaxy.star(function(cb) { | |
for (var i = 0; i < futures.length; i++) { | |
galaxy.unstar(futures[i], 0)(function(e, r) { | |
if (cb) cb(e, r); | |
cb = null; | |
}); | |
} | |
}, 0)(); | |
} | |
var sleep = galaxy.star(function(ms, cb) { | |
setTimeout(cb, ms); | |
}, 1); | |
function *delay(ms, result) { | |
yield sleep(ms); | |
return result; | |
} | |
function *test() { | |
var futs = [10, 4, 2, 6].map(function(i) { | |
return galaxy.spin(delay(i * 100, i)); | |
}); | |
var result = yield waitForOne(futs); | |
console.log("result=" + result); | |
} | |
galaxy.unstar(test)(function(err) { | |
if (err) throw err; | |
}); |
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
"use strict"; | |
function waitForOne(cb, futures) { | |
for (var i = 0; i < futures.length; i++) { | |
futures[i](function(e, r) { | |
if (cb) cb(e, r); | |
cb = null; | |
}); | |
} | |
} | |
function delay(_, ms, result) { | |
setTimeout(_, ms); | |
return result; | |
} | |
function test(_) { | |
var futs = [10, 4, 2, 6].map(function(i) { | |
return delay(!_, i * 1000, i); | |
}); | |
var result = waitForOne(_, futs); | |
console.log("result=" + result); | |
} | |
test(function(err) { | |
if (err) throw err; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
added
waitForOne._js
: same example, but written with streamline.js