diff --git a/index.js b/index.js index ff6bf15..0593d70 100644 --- a/index.js +++ b/index.js @@ -1,26 +1,36 @@ +var __slice = [].slice + module.exports = function (procedure, subsequent) { - var running, waiting, callbacks = [] + var running, waiting, callbacks = { queue: [] } function run (callback) { if (callback) { - callbacks.push(callback) + callbacks.queue.push(callback) } if (!running) { running = true + callbacks.next = callbacks.queue.splice(0, callbacks.queue.length) + if (subsequent) { + callbacks.next.unshift(subsequent) + } try { procedure(function () { + var vargs = __slice.call(arguments) running = false - subsequent.apply(null, arguments) - while (callbacks.length) { - callbacks.shift().apply(null, arguments) - } + callbacks.next.splice(0, callbacks.next.length).forEach(function (callback) { + callback.apply(null, vargs) + }) if (waiting) { waiting = false run() } }) - } catch (e) { + } catch (error) { running = false - subsequent(e) + if (callbacks.next.length) { + callbacks.next.forEach(function (callback) { callback.call(null, error) }) + } else { + throw error + } } } else { waiting = true diff --git a/release.md b/release.md new file mode 100644 index 0000000..1945dc9 --- /dev/null +++ b/release.md @@ -0,0 +1,3 @@ +### Issue by Issue + + * Slice a copy of outstanding callbacks. #19. diff --git a/t/turnstile/throw.t.js b/t/turnstile/throw.t.js index b06e355..08a11a2 100644 --- a/t/turnstile/throw.t.js +++ b/t/turnstile/throw.t.js @@ -1,9 +1,19 @@ -require('proof')(1, function (step, assert) { - var results = [], pause - var turnstile = require('../..')(function (callback) { +require('proof')(2, function (step, assert) { + var results = [], turnstile + turnstile = require('../..')(function (callback) { throw new Error('abend') }, function (error) { assert(error.message, 'abend', 'caught') }) turnstile() + turnstile = require('../..')(function (callback) { + callback(new Error('abend')) + }) + try { + turnstile(function (error) { + throw error + }) + } catch (error) { + assert(error.message, 'abend', 'uncaught') + } })