Created
April 30, 2013 02:09
-
-
Save Raynos/5486218 to your computer and use it in GitHub Desktop.
Async mapping with continuable
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 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