Before promises, asynchronous work in JavaScript reported back through callbacks: you passed a function, and the work called it later with (error, value). Many tasks still have to happen in order: read a config file, then connect with what it says, then load the first page of data. Each step must wait for the one before it, and one failure must stop the rest.
Write runInSequence(tasks, done) in sequence.js. It runs callback-style tasks one after another, collects their values in order, and reports once to done.
tasks: an array of functions. Each has the form task(callback) and calls callback(error, value) when it finishes, usually later from a timer or an event.
done: called once at the end, as done(null, results) on success or done(error) on failure.
An error is a truthy first argument. null, undefined and false mean success.
The first task starts during the call to runInSequence.
Each next task starts only after the previous one called back without an error, and at once when it does.
When every task has succeeded, done(null, results) is called, with results holding each task's value in task order (a task that calls back with no value gives undefined).
At the first error, done(error) is called at once with that error and no results, and no later task starts.
done is called exactly once. If a task calls its callback a second time, the second call is ignored, whatever it holds.
An empty array calls done(null, []).
Tasks may call back synchronously, inside the task(callback) call itself; that must still work, however many tasks there are: 100,000 tasks that all call back synchronously must not run out of call stack.
The tasks array is not changed, and two runs at the same time do not share results.
runInSequence returns undefined: the results go to done.