Skip to content

Instantly share code, notes, and snippets.

@Raynos
Created April 30, 2013 02:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Raynos/5486218 to your computer and use it in GitHub Desktop.
Save Raynos/5486218 to your computer and use it in GitHub Desktop.
Async mapping with continuable
var assert = require('assert')
var setTimeout = require('timers').setTimeout
var list = [1, 2, 3, 4, 5]
var conts = list.map(function (n) {
return function continuable(cb) {
setTimeout(function () {
cb(null, n * 2)
}, 10)
}
})
var answer = list(conts)(function (err, results) {
assert.deepEqual(results, [2, 4, 6, 8, 10])
})
// https://gist.github.com/Raynos/5486205
// lists := (tasks:Array<Continuable<T>>)
// => Continuable<Array<T>>
function list(tasks) {
return function continuable(callback) {
var result = []
var ended = false
var count = 0
var length = tasks.length
tasks.forEach(function (source, index) {
source(function (err, value) {
if (err && !ended) {
callback(err)
} else if (!err) {
result[index] = value
if (++count === length) {
callback(null, result)
}
}
})
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment