From d2fe2b323820f4fbce268ade71435d58088118bb Mon Sep 17 00:00:00 2001 From: Alexander Early Date: Sun, 6 Mar 2016 17:33:08 -0800 Subject: defend against multiple callbacks --- lib/waterfall.js | 34 +++++++++++++++++++--------------- 1 file changed, 19 insertions(+), 15 deletions(-) (limited to 'lib/waterfall.js') diff --git a/lib/waterfall.js b/lib/waterfall.js index 8867c87..e25f629 100644 --- a/lib/waterfall.js +++ b/lib/waterfall.js @@ -5,28 +5,32 @@ import noop from 'lodash/noop'; import once from 'lodash/once'; import rest from 'lodash/rest'; -import ensureAsync from './ensureAsync'; -import iterator from './iterator'; +import onlyOnce from './internal/onlyOnce'; export default function(tasks, cb) { cb = once(cb || noop); if (!isArray(tasks)) return cb(new Error('First argument to waterfall must be an array of functions')); if (!tasks.length) return cb(); + var taskIndex = 0; - function wrapIterator(iterator) { - return rest(function(err, args) { + function nextTask(args) { + if (taskIndex === tasks.length) { + return cb.apply(null, [null].concat(args)); + } + var task = tasks[taskIndex]; + taskIndex++; + + var taskCallback = onlyOnce(rest(function(err, args) { if (err) { - cb.apply(null, [err].concat(args)); - } else { - var next = iterator.next(); - if (next) { - args.push(wrapIterator(next)); - } else { - args.push(cb); - } - ensureAsync(iterator).apply(null, args); + return cb.apply(null, [err].concat(args)); } - }); + nextTask(args); + })); + + args.push(taskCallback); + + task.apply(null, args); } - wrapIterator(iterator(tasks))(); + + nextTask([]); } -- cgit v1.2.1