index.js 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. 'use strict'
  2. var nextTick = nextTickArgs
  3. process.nextTick(upgrade, 42) // pass 42 and see if upgrade is called with it
  4. module.exports = thunky
  5. function thunky (fn) {
  6. var state = run
  7. return thunk
  8. function thunk (callback) {
  9. state(callback || noop)
  10. }
  11. function run (callback) {
  12. var stack = [callback]
  13. state = wait
  14. fn(done)
  15. function wait (callback) {
  16. stack.push(callback)
  17. }
  18. function done (err) {
  19. var args = arguments
  20. state = isError(err) ? run : finished
  21. while (stack.length) finished(stack.shift())
  22. function finished (callback) {
  23. nextTick(apply, callback, args)
  24. }
  25. }
  26. }
  27. }
  28. function isError (err) { // inlined from util so this works in the browser
  29. return Object.prototype.toString.call(err) === '[object Error]'
  30. }
  31. function noop () {}
  32. function apply (callback, args) {
  33. callback.apply(null, args)
  34. }
  35. function upgrade (val) {
  36. if (val === 42) nextTick = process.nextTick
  37. }
  38. function nextTickArgs (fn, a, b) {
  39. process.nextTick(function () {
  40. fn(a, b)
  41. })
  42. }