Sha256: a5e23c674525fc252129cef379c7a45af656553bdf23d8a49c364e1f51aa133c

Contents?: true

Size: 1.34 KB

Versions: 24

Compression:

Stored size: 1.34 KB

Contents

'use strict'

var slice = [].slice

module.exports = wrap

// Wrap `fn`.
// Can be sync or async; return a promise, receive a completion handler, return
// new values and errors.
function wrap(fn, callback) {
  var invoked

  return wrapped

  function wrapped() {
    var params = slice.call(arguments, 0)
    var callback = fn.length > params.length
    var result

    if (callback) {
      params.push(done)
    }

    try {
      result = fn.apply(null, params)
    } catch (error) {
      // Well, this is quite the pickle.
      // `fn` received a callback and invoked it (thus continuing the pipeline),
      // but later also threw an error.
      // We’re not about to restart the pipeline again, so the only thing left
      // to do is to throw the thing instead.
      if (callback && invoked) {
        throw error
      }

      return done(error)
    }

    if (!callback) {
      if (result && typeof result.then === 'function') {
        result.then(then, done)
      } else if (result instanceof Error) {
        done(result)
      } else {
        then(result)
      }
    }
  }

  // Invoke `next`, only once.
  function done() {
    if (!invoked) {
      invoked = true

      callback.apply(null, arguments)
    }
  }

  // Invoke `done` with one value.
  // Tracks if an error is passed, too.
  function then(value) {
    done(null, value)
  }
}

Version data entries

24 entries across 24 versions & 1 rubygems

Version Path
trusty-cms-6.3.1 node_modules/trough/wrap.js
trusty-cms-5.0.7 node_modules/trough/wrap.js
trusty-cms-5.0.6 node_modules/trough/wrap.js
trusty-cms-5.0.5 node_modules/trough/wrap.js
trusty-cms-5.0.4 node_modules/trough/wrap.js
trusty-cms-5.0.3 node_modules/trough/wrap.js
trusty-cms-5.0.2 node_modules/trough/wrap.js
trusty-cms-5.0.1 node_modules/trough/wrap.js
trusty-cms-4.3.5 node_modules/trough/wrap.js
trusty-cms-5.0.0 node_modules/trough/wrap.js
trusty-cms-4.3.4 node_modules/trough/wrap.js
trusty-cms-4.3.3 node_modules/trough/wrap.js
trusty-cms-4.3.2 node_modules/trough/wrap.js
trusty-cms-4.3.1 node_modules/trough/wrap.js
trusty-cms-4.3 node_modules/trough/wrap.js
trusty-cms-4.2.3 node_modules/trough/wrap.js
trusty-cms-4.2.2 node_modules/trough/wrap.js
trusty-cms-4.2.1 node_modules/trough/wrap.js
trusty-cms-4.2 node_modules/trough/wrap.js
trusty-cms-4.1.9 node_modules/trough/wrap.js