public
Last active

  • Download Gist
chain.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
var makeArray = Function.prototype.call.bind(Array.prototype.slice)
 
function chaining(actions, initialParams) {
var action = actions.shift()
if (!action) return
 
function innerCallback(err) {
initialParams.shift()
var newParams = makeArray(arguments)
, passingParams = newParams.concat(initialParams)
chaining(actions, passingParams)
}
 
action.apply(innerCallback, initialParams)
}
 
function chain() {
var actions = makeArray(arguments)
process.nextTick(function() {
chaining(actions, [])
})
}
 
module.exports = chain
test.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
var chain = require('./chain')
, assert = require('assert')
, recording = {steps: 3}
 
chain(
function() {
recording.steps--
setTimeout(this, 5, NaN, 1)
}
, function(err, one) {
recording.steps--
assert.notStrictEqual(err, err, "It's NaN")
assert.equal(one, 1, "Gotcha")
recording.status = 0
process.nextTick(this.bind(null, Error(), 2, "42"))
}
, function(err, two, answer, one) {
recording.steps--
assert.ok(err instanceof Error)
assert.equal(answer, 42)
assert.equal(one, 1, "You again, huh?")
assert.equal(arguments.length, two * two)
}
)
 
setTimeout(function() {
process.exit(recording.steps)
}, 50)

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.