Call `func` after `obj` has been resolved. Call `func` synchronously if `obj` is not a promise for performance reasons.
328356
function after(obj, func) {
  if (isPromise(obj)) {
    return obj.then(func);
  } else {
    return func(obj);
  }
}
191950
def promise_method(func):
    
    name = func.__name__

    @wraps(func)
    def wrapped(self, *args, **kwargs):
        cls_name = type(self).__name__
        if getattr(self, '_%s__resolved' % (cls_name,)):
            return getattr(getattr(self, '_%s__wrapped' % (cls_name,)), name)(*args, **kwargs)
        return func(self, *args, **kwargs)
    return wrapped
1311356
def call_sync(func):
    """"""

    @wraps(func)
    def wrapper(self, *args, **kw):
        """Wraps instance method to be called on loop thread"""

        # Just return when already on the event thread
        if self.thread.ident == get_ident():
            return func(self, *args, **kw)

        barrier = Barrier(2)
        result = None
        ex = None

        def call():
            """Calls function on loop thread"""
            nonlocal result, ex
            try:
                result = func(self, *args, **kw)
            except Exception as exc:
                ex = exc
            finally:
                barrier.wait()

        self.loop.call_soon_threadsafe(call)
        barrier.wait()
        if ex:
            raise ex or Exception("Unknown error")
        return result

    return wrapper
370115
function whenDone (val, fn) {
  if (isPromise(val)) {
    return val.done(fn);
  } else {
    return fn(val);
  }
}
740359
function when(){
		// handle if we get called with a function
		var args = makeArray(arguments),
			last = args[args.length -1];
			
		if(typeof last === 'function' ){
			args[args.length -1] = {
				'fn' : last
			}
			args.push("fn");
		};
		
		var waitMeth = args.pop(), 
			waitObj = args.pop(),
			joined = new join(waitObj, waitMeth); 
		
		for(var i =0; i < args.length; i = i+2){
			joined.add(args[i], args[i+1])
		}
		
		// call right away if it should
		joined.go();
	}
1252804
function(fn) {
				if (typeof fn === 'object' && fn.then && fn.catch) {
					var defer = fn;
					fn = function(resolve, reject) {
						defer.then(resolve).catch(reject);
					};
				}
				funcGuard(fn);
				if (err !== undefined) {
					return;
				} else if (complete) {
					throw new Error('Queue already completed');
				}

				tasks.push(fn);
				++remaining;
				pop();
				return q;
			}
335459
def async_call(func, *args, callback=None):
    '''
    '''
    def do_call():
        result = None
        error = None

        try:
            result = func(*args)
        except Exception:
            error = traceback.format_exc()
            logger.error(error)
        if callback:
            GLib.idle_add(callback, result, error)

    thread = threading.Thread(target=do_call)
    thread.daemon = True
    thread.start()
1020653
function runAfterDetach (args, methodMeta, ret) {
    // skip if no afterDetach methods
    if (!defined(methodMeta.afterDetach)) {
        return
    }
    // wait for original promise to resolve then run detached after functions
    ret.then(res => {
        // build arguments for after methods
        args = {
            args: args.args ? args.args : args,
            res: res,
            origRes: args.origRes ? args.origRes : args.res,
            session: args.session,
        }
        // run all functions
        _.each(methodMeta.afterDetach, method => {
            // call method
            (method)(args, methodMeta.signature, 'afterDetach')
            // log errors
            .catch(err => {
                // require log client
                if (!defined(methodMeta.logClient)) {
                    return
                }
                // log error
                methodMeta.logClient.error(err, args.session)
            })
        })
    })
}
684116
function async (f, args) {
    new Promise(invoke).then(function asyncFulfill () {
      return f.apply(null, args);
    });
  }
321802
function resolver(obj) {
  return new Promise(function(resolve, reject) {
    _.isEmpty(obj.results) ? reject(new Error(JSON.stringify(obj.errors))) : resolve(obj.results);
  })
}
284281
function runAsync(context, func, callback)
{
  var result
    , requiresContext = isArrowFunction(func)
    ;

  if (requiresContext)
  {
    result = func.call(null, context, callback);
  }
  else
  {
    result = func.call(context, callback);
  }

  return result;
}
191980
function (callback) {
        after("helper.after", function () {
            return bluebird.resolve()
                .then(function() {
                    if (_.isFunction(callback)) {
                        return callback();
                    }
                })
                .then(helper.stop.bind(helper));
        });
    }
511914
function promisesWrapper(func) {
    return (options, callback) => {
        // options is an optional argument
        if (typeof options === 'function') {
            callback = options;
            options = undefined;
        }
        options = options || {};
        // just call the function otherwise wrap a promise around its execution
        if (typeof callback === 'function') {
            func(options, callback);
            return undefined;
        } else {
            return new Promise((fulfill, reject) => {
                func(options, (err, result) => {
                    if (err) {
                        reject(err);
                    } else {
                        fulfill(result);
                    }
                });
            });
        }
    };
}
1251524
def async_(fn):
    """"""
    @functools.wraps(fn)
    async def wrapper(*args, **kwargs):
        return await fn(*args, **kwargs)
    return wrapper
551491
function (next) {  // next can be a function or another thenable
             if (typeof(next.then) === 'function')  // thenable?
               return next
             // next is a function, so call it
             var nextResult = next.apply (next, result)
             if (nextResult && typeof(nextResult.then) !== 'undefined')  // thenable?
               return nextResult
             // create a Promise-like wrapper for the result
             return syncPromiseResolve (nextResult)
           }
1009928
function then(resolver, onFulfilled, onRejected) {
        var res = new Resolver();
        var promise = createPromise(res);

        if (isFunction(onFulfilled)) {
            onFulfilled = wrapCallback(res, promise, onFulfilled);
        }
        else {
            // not function
            // 'return promise' must fulfill with the same value
            // when 'main promise' is resolved
            // see #2.2.7.3
            onFulfilled = function (data) {
                res.fulfill(data);
            };
        }
        addListener(resolver, STATUS.FULFILLED, onFulfilled);

        if (isFunction(onRejected)) {
            onRejected = wrapCallback(res, promise, onRejected);
        }
        else {
            // not function
            // 'return promise' must reject with the same reason
            // when 'main promise' is rejected
            // see #2.2.7.4
            onRejected = function (reason) {
                res.reject(reason);
            };
        }
        addListener(resolver, STATUS.REJECTED, onRejected);

        return promise;
    }
965716
function runWithAfter (ret, runWith) {
    // after original promise resolves then run after methods
    return ret.then(res => {
        // wait for all extension methods to complete
        return Promise.all(runWith)
        // merge returned data into original
        .then(function (results) {
            // either merge or replace result
            _.each(results, result => {
                // both original res and after result are objects
                if (typeof res === 'object' && res !== null && typeof result === 'object' && result !== null) {
                    // merge after into original
                    _.merge(res, result)
                }
                // one is not an object
                else if (result !== undefined) {
                    // replace original with after
                    res = result
                }
            })
            // return final result
            return res
        })
    })
}