Wrap a promise-returning function
into a function that accepts a
node.js style callback.
@param {AsyncFunction} func
@returns {Function}
354562
function callbackify(func) {
  return function(...args) {
    if (args.length === 0
        || typeof args[args.length - 1] !== 'function') {
      throw new Error(`${func.name || 'Function'} requires a callback.`);
    }

    const callback = args.pop();

    func.call(this, ...args).then((value) => {
      setImmediate(() => callback(null, value));
    }, (err) => {
      setImmediate(() => callback(err));
    });
  };
}
33852
def wrap(self, func, delay=0):
        '''
        
        '''
        def wrapped():
            self.start()
            if delay:
                self.sleep(delay)
            x = None
            try:
                x = func()
            except OSError as oserror:
                log.debug('OSError exception:%s', oserror)
                self.oserror = oserror
                raise EasyProcessError(self, 'wrap error!')
            finally:
                self.stop()
            return x
        return wrapped
555159
function Promise(callback, handler) {
			// The `handler` variable points to the function that will
			// 1) handle a .then(resolved, rejected) call
			// 2) handle a resolve or reject call (if the first argument === `is`)
			// Before 2), `handler` holds a queue of callbacks.
			// After 2), `handler` is a finalized .then handler.
			handler = function pendingHandler(resolved, rejected, value, queue, then, i) {
				queue = pendingHandler.q;

				// Case 1) handle a .then(resolved, rejected) call
				if (resolved != is) {
					return Promise(function (resolve, reject) {
						queue.push({ p: this, r: resolve, j: reject, 1: resolved, 0: rejected });
					});
				}

				// Case 2) handle a resolve or reject call
				// (`resolved` === `is` acts as a sentinel)
				// The actual function signature is
				// .re[ject|solve](<is>, success, value)

				// Check if the value is a promise and try to obtain its `then` method
				if (value && (is(func, value) | is(obj, value))) {
					try { then = value.then; }
					catch (reason) { rejected = 0; value = reason; }
				}
				// If the value is a promise, take over its state
				if (is(func, then)) {
					function valueHandler(resolved) {
						return function (value) { then && (then = 0, pendingHandler(is, resolved, value)); };
					}
					try { then.call(value, valueHandler(1), rejected = valueHandler(0)); }
					catch (reason) { rejected(reason); }
				}
				// The value is not a promise; handle resolve/reject
				else {
					// Replace this handler with a finalized resolved/rejected handler
					handler = function (Resolved, Rejected) {
						// If the Resolved or Rejected parameter is not a function,
						// return the original promise (now stored in the `callback` variable)
						if (!is(func, (Resolved = rejected ? Resolved : Rejected)))
							return callback;
						// Otherwise, return a finalized promise, transforming the value with the function
						return Promise(function (resolve, reject) { finalize(this, resolve, reject, value, Resolved); });
					};
					// Resolve/reject pending callbacks
					i = 0;
					while (i < queue.length) {
						then = queue[i++];
						// If no callback, just resolve/reject the promise
						if (!is(func, resolved = then[rejected]))
							(rejected ? then.r : then.j)(value);
						// Otherwise, resolve/reject the promise with the result of the callback
						else
							finalize(then.p, then.r, then.j, value, resolved);
					}
				}
			};
			// The queue of pending callbacks; garbage-collected when handler is resolved/rejected
			handler.q = [];

			// Create and return the promise (reusing the callback variable)
			callback.call(callback = { then:    function (resolved, rejected) { return handler(resolved, rejected); },
					"catch": function (rejected)           { return handler(0,        rejected); } },
				function (value)  { handler(is, 1,  value); },
				function (reason) { handler(is, 0, reason); });
			return callback;
		}
702125
function wrapify(fn, before = noop, after = noop) {
  return function(...args) {
    before.call(this);
    var ret = fn.call(this, ...args);
    after.call(this);
    return ret;
  };
}
275866
function promisify(func) {
        return function(str, options) {
            var result,
                deferred = q.defer(),
                promise = deferred.promise;

            if (!_.isFunction(func)) {
                deferred.reject();
            }
            else {
                result = func(str, options);

                if (_.isBoolean(result)) {
                    promise = handleBoolean(result, deferred);
                }
                else if (_.isFunction(result.then)) {
                    promise = result;
                }

            }
            return promise;
        };
    }
167316
function bind (fn) {
          if (typeof fn !== 'function') return fn
          return ins.bindFunction(function (val) {
            var result = (promise.__ob_wrapper || propagateObWrapper)(this, fn, val, next)
            if (result.error) {
              throw result.errorVal
            } else {
              return result.returnVal
            }
          })
        }
755522
function(callback) {
		this.promises.push(function async(done, utils) {
			callback(utils.lastReturn, done, utils);
		});
		return this;
	}
194065
function async(f, args) {
    return new Promise(
      function(resolve, reject) {
        try {
          var r = f.apply(undefined, args);
          resolve(r);
        } catch(e) {
          reject(e);
        }
      }
    );
  }
109811
function promisify(original, self = null) {
  if (typeof original !== 'function') {
    throw new TypeError('original must be a function')
  }

  /**
   * Wrapped original function.
   * @typedef {function} wrapper
   * @param {...*} args - Arguments to apply to the original function.
   * @returns {Promise.<*>} - Promise that gets resolved when the original function calls the callback.
   */
  function wrapper(...args) {
    let thisArg = self
    if (this !== global) {
      // called with bound this object
      thisArg = this
    }

    if (typeof args[args.length - 1] === 'function') {
      // called with callback
      return original.call(thisArg, ...args)
    }

    // promisified
    return new Promise((resolve, reject) => {
      /**
       * Callback for the original function.
       * @typedef {function} cb
       * @param {?Error} error - Error if one occured.
       * @param {*} result - Result of the original function.
       */
      function cb(error, result) {
        if (error) {
          return reject(error)
        }
        resolve(result)
      }

      args.push(cb)

      original.call(thisArg, ...args)
    })
  }

  return wrapper
}
450812
function utilCallbackAfterPromise(self, func, args, cb) {
	args = Array.prototype.slice.apply(args);
	let lastarg = args.pop();
	if(!cb) cb = lastarg;
	func.apply(self, args).then(res => {
		try {
			cb(null, res);
		} catch(e) {
			process.nextTick(() => { throw e });
		}
	}).catch((err) => {
		try {
			cb(err);
		} catch(e) {
			process.nextTick(() => { throw e });
		}
	});
}
1330346
function promisify(func) {
  return function promisified() {
    var args = Array.prototype.slice.call(arguments);
    var context = this;

    return new Promise(function(resolve, reject) {
      try {
        func.apply(context, args.concat(function(err, data) {
          if (err) {
            return reject(err);
          }

          resolve(data);
        }));
      } catch(err) {
        reject(err);
      }
    });
  };
}
452963
function wrap(func) {
  if (!util.is('Function', func)) { func = function noop(){}; }

  return function wrapper() {
    try {
      return func.apply(this, arguments);
    } catch(err) {
      this.notify(err, {stackShift: 3});
      throw(err);
    }
  }.bind(this);
}
960975
function promisify(f) {                              // given an underlying function,
  return function _promisify(...args) {              // return a function which
    return new Promise(                              // returns a promise
      resolve => Promise.all([this, ...args])        // which, when all args are resolved,
        .then(
          parms => resolve(f.call(...parms))         // resolves to the function result
        )
    );
  };
}
709886
function wrapQueryMethod(fn, ctx) {
    return function() {
        // Obtain function arguments
        var args = [].slice.call(arguments);
        
        // Return a thunkified function that receives a done callback
        return function(done) {
            // Add a custom callback to provided args
            args.push(function(err, result) {
                // Query failed?
                if (err) {
                    return done(err);
                }

                // Query succeeded
                done(null, result);
            });

            // Execute the query
            fn.apply(ctx, args);
        };
    };
}
817301
function async(fn) {
  return function asynced(done) {
    var err, ret;
    try {
      ret = fn();
    } catch (e) {
      err = e;
    } finally {
      if (err) {
        done(err);
      } else {
        done(null, ret);
      }
    }
  };
}
129189
function makeMethod(func) {
	return function() {
		var args = [this].concat(slice.call(arguments));
		return func.apply(null, args);
	};
}
763093
function serialized(func) {
  var currentPromise = null;
  var wrapped = function() {
    var self = this;
    var args = arguments;
    if (currentPromise) {
      return currentPromise.fin(function() {
        return wrapped.apply(self, args);
      });
    }

    currentPromise = func.apply(self, args);
    
    currentPromise
    .fin(function() {
      currentPromise = null;
    })
    .eat();
    
    return currentPromise;
  };
  return wrapped;
}