This invoke function is written in a style that assumes some calling function (or Promise) will handle exceptions.
196561
function invoke(method, arg) {
          var result = generator[method](arg);
          var value = result.value;
          return value instanceof AwaitArgument
            ? Promise.resolve(value.arg).then(invokeNext, invokeThrow)
            : Promise.resolve(value).then(function(unwrapped) {
            // When a yielded Promise is resolved, its final value becomes
            // the .value of the Promise<{value,done}> result for the
            // current iteration. If the Promise is rejected, however, the
            // result for this iteration will be rejected with the same
            // reason. Note that rejections of yielded Promises are not
            // thrown back into the generator function, as is the case
            // when an awaited Promise is rejected. This difference in
            // behavior between yield and await is important, because it
            // allows the consumer to decide what to do with the yielded
            // rejection (swallow it and continue, manually .throw it back
            // into the generator, abandon iteration, whatever). With
            // await, by contrast, there is no opportunity to examine the
            // rejection reason outside the generator function, so the
            // only option is to throw it from the await expression, and
            // let the generator function handle the exception.
            result.value = unwrapped;
            return result;
          });
        }
115393
function invokeFunctionHandler(handler, args, checkArity, req, res, done) {
  // check if number of arguments provided matches the handler function arity
  if (checkArity && args.length < handler.length) { // < due to possible optionals
    done(new ModofunError(400, 'InvalidInput',
      `This operation requires ${handler.length} parameters. Received ${args.length}.`));
    return;
  }
  // set this in function call to the remaining relevant request data
  // could consider pushing the whole request object instead?
  // for now prefer to keep it to minimum to allow maximum flexibility
  const thisArg = {
    method: req.method,
    headers: req.headers,
    body: req.body,
    query: req.query,
    user: req.user
  };
  // call handler function with
  let result = handler.apply(thisArg, args);
  // handle results that are not a trusted Promise with Promise.resolve()
  // which also supports other then-ables
  if (result instanceof Promise === false) {
    result = Promise.resolve(result);
  }
  return result
    .then(value => {
      if (value === null) {
        done(new ModofunError(404, 'NullResponse', `${req.path} resource was not found`));
        return;
      }
      if (value === undefined || value === '') {
        res.status(204).end();
      } else {
        res.status(200).json(value);
      }
      done();
    })
    .catch(done);
}
762569
function callAction(request, response, callback) {
    if (typeof callback == 'function') {
      return Promive.resolve()
        .then(callback.bind(null, request, response));
    }

    try {
      var Action = require(ACTION_PATH + '/' + callback.action + '.js');
    } catch (error) {
      if (error.message == 'Cannot find module \'' + ACTION_PATH + '/' + callback.action + '.js\'') {
        return Promise.reject('Action ' + callback.action + ' does not exist.')
          .catch(this.onPageNotFound.bind(this, request, response));
      }
      return Promise.reject(error)
        .catch(this.onError.bind(this, request, response));
    }

    var instance = new Action(request, response);
    // Test if method exists
    if (!instance[callback.method]) {
      return Promise.reject(new Error('Method "' + callback.method + '" not found in action "' + callback.action + '"'));
    }

    var promise = Promise.resolve();
    if (instance.init && 'function' == typeof instance.init) {
      promise = promise.then(function () {
        return instance.init();
      });
    }

    promise = promise.then(function () {
      return instance[callback.method].apply(instance, callback.arguments);
    });

    if (instance.onError && 'function' == typeof instance.onError) {
      promise = promise.catch(function (error) {
        return instance.onError.call(instance, error)
      });
    }

    promise = promise.catch(this.onError.bind(this, request, response));

    return promise;
  }
237212
function makePromise(fn) {
	return function() {
		var args = Array.prototype.slice.call(arguments);
		if (hasCallback(args)) {
			// argument list has callback, so call method with callback
			return callCallback(fn, args);
		} else {
			// no callback, call method with promises
			return callPromise(fn, args);
		}
	}
}
416178
function errorToExceptionCallback(cb) {
    var browser = this;

    return function errorWrapped(err) {
        if (err) throw err;
        if (cb) {
            cb.apply(browser, _.tail(arguments));
        }
    };
}
406364
function wrap (func) {
  return () => new Promise((resolve, reject) => {
    func()
      .then(x => resolve(x))
      .catch(err => {
        let status = _get(err, 'response.status')
        let text = _get(err, 'content.text')

        if (status || text) {
          console.warn(`API error: ${text} (${status})`)
          return resolve(null)
        }

        reject(err)
      })
  })
}
404788
def safecall(func):
    """"""
    def wrapper(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except Exception:
            pass
    return wrapper
1096790
function promiseOrCallback (callback, executor) {
    var promise = new Promise(executor);

    // no callback: do not attach
    if (typeof callback !== 'function') {
        return promise;
    }

    return promise.then(function (value) {
        setImmediate(function () {
            callback(null, value);
        });
        return value;
    }, function (error) {
        setImmediate(function () {
            callback(error);
        });
        throw error;
    });
}
852655
function (args, onDone, extra) {
		// if args are not provided then we shift the parameters
		if (typeof args === 'function') {
			extra = onDone;
			onDone = args;
			args = {};
		}

		// TODO: perform argument type check (currently there's none, so internal API calls won't do type checks)
		// TODO: move checker to here

		var onError = function(err) {
			LOG.error('onError '+ err, l_name);
			UTIL.safeCall(onDone, err);
		}

		function onExec() {
			// make actual call to user-defined function
			// NOTE: we also return values for direct function calls
			return UTIL.safeCall(l_list[name], args, function (err, result, unsupported_return) {
				if (err) {
					LOG.error('[' + name + '] error:', l_name);
					LOG.error(err, l_name);
				}

				if (unsupported_return) {
					var errmsg = 'onDone() in SR.API does not support more than one return variable, please return everything inside a result object';
					LOG.error(errmsg, l_name);
					LOG.stack();
					return UTIL.safeCall(onDone, errmsg);
				}

				// perform post-event actions, if any
				if (l_afterActions.hasOwnProperty(name) === false) {
					return UTIL.safeCall(onDone, err, result);
				}

				var posts = l_afterActions[name];
				var promise = undefined;
				for (var i=0; i < posts.length; i++) {
					if (!promise) {
						promise = post_action(args, { err: err, result: result }, posts[i], extra);
					} else {
						promise = promise.then(post_action(args, { err: err, result: result }, posts[i], extra));
					}
				}

				// last action
				promise.then(new SR.promise(function (resolve, reject) {
					//LOG.warn('everything is done... call original onDone...', l_name);
					UTIL.safeCall(onDone, err, result);
					resolve();
				}));

			}, extra);
		}

		// perform pre-event actions, if any
		if (l_beforeActions.hasOwnProperty(name) === false) {
			return onExec();
		}

		const pres = l_beforeActions[name].map((callback) => pre_action(args, callback, extra));
		pres.reduce((p, callback) => p.then(() => callback), Promise.resolve())
			.then(onExec)
			.catch((err) => {
				LOG.error(err);
				onDone(err);
			});
	}
537211
public static AsyncCallback<String> wrapCallback(final JavaScriptObject func) {

        return new AsyncCallback<String>() {

            public void onFailure(Throwable caught) {

                // TODO Auto-generated method stub

            }

            public void onSuccess(String result) {

                callWithString(func, result);
            }

        };
    }
77630
function wrapFn(fn) {

  var argCount = fn.length;

  if (argCount < 2) {
    // promise style worker
    return async function(context) {
      return await fn(context);
    };
  }

  if (argCount === 2) {
    // callback style worker
    return function(context) {

      return new Promise(function(resolve, reject) {
        try {
          fn(context, function(err, data) {
            if (err) {
              reject(err);
            } else {
              resolve(data);
            }
          });
        } catch (err) {
          reject(err);
        }
      });

    };
  }

  throw new Error('expected Promise or callback style fn');
}
686365
function _handlePromiseOrValue(promiseOrValue, cb) {
    if (promiseOrValue && promiseOrValue.then && typeof promiseOrValue.then === "function") {
        promiseOrValue
            .then(function(value) {
                cb(null, value);
            })
            .catch(function(err) {
                cb(err);
            });
    }  else {
        cb(null, promiseOrValue);
    }
}
1287601
function enter(f, rejected) {
	return function() {
		try {
			return Promise.resolve(f.apply(this, arguments)).catch(rejected)
		}
		catch(e) { return rejected(e) }
	}
}
704563
function invoke(inst, list, argv, event, fin) {
    // All invocations cost some amount just for running
    if (!ok(inst, inst.options.invokeTransaction)) return exit(inst, list, fin);
    var name = _getFnName(list);
    var args = _getFnArgs(list);
    var library = inst.library;
    var lookup;

    // Prepare the arguments and context
    _unquoteArgs(args);
    _valuefyArgs(args, library);
    var ctx = {
        id: inst.counter,
        seed: inst.seednum,
        store: inst.storage,
        name: name,
        list: list,
        args: args,
        argv: argv,
        event: event,
        cb: fin
    };

    // Function (or global fallback)
    lookup = library.lookupFunction(name);
    if (!_isPresent(lookup)) {
        var missing = inst.options.functionMissingName;
        var fallback = library.lookupFunction(missing);
        if (fallback) {
            lookup = fallback;
            name = missing;
        }
    }
    if (lookup) {
        // The library may define function prices
        var price = library.lookupPrice(name);
        if (_isPresent(price)) {
            if (!ok(inst, -price)) {
                return exit(inst, list, fin);
            }
        }
        // Type checking
        if (inst.options.doRuntimeTypeCheck) {
            var typeError = Types.runtimeCheck(inst, name, library, args);
            if (typeError) return fin(_wrapError(typeError, inst, list), null);
        }
        if (library.isImpureFunction(name)) {
            if (!inst.options.doAllowImpureFunctions) {
                return fin(_wrapError(_impurityError(inst), inst, list), null);
            }
            if (inst.options.doWarnOnImpureFunctions) {
                Console.printWarning(inst, 'Function `' + name + '` is labeled impure');
            }
        }
        var invokeArgs = args.concat(passthrough(fin));
        return lookup.apply(ctx, invokeArgs);
    }

    // Type conversion
    lookup = library.lookupTypeCaster(name);
    if (lookup) {
        return fin(null, lookup.apply(ctx, args));
    }

    // Constant
    lookup = library.lookupConstant(name);
    if (_isPresent(lookup)) {
        if (args.length < 1) return fin(null, lookup);
        list[RUNIQ_INDEX_OF_FUNCTION_NAME] = lookup;
        return fin(null, list);
    }

    // Without any args present, return the string
    if (args.length < 1) return fin(null, name);

    // If no other option, just return the entire list
    return fin(null, list);
}
505553
function tryCallback(callback, args) {
  try {
    return callback.apply(this, args);
  } catch (e) {
    if (typeof e === 'string') {
      return new binding.types.Error(e);
    } else if (e instanceof Error) {
      return new binding.types.Error(e.message);
    } else {
      return new binding.types.Error('An unexpected error occurred');
    }
  }
}
184297
function coerce(promise) {
        var deferred = defer();
        nextTick(function () {
            try {
                promise.then(deferred.resolve, deferred.reject, deferred.notify);
            } catch (exception) {
                deferred.reject(exception);
            }
        });
        return deferred.promise;
    }
152053
function FunctionCall( fn , isAsync , thisArg , ... args ) {
	this.function = fn ;
	this.isAsync = isAsync ;
	this.this = thisArg ;
	this.args = args ;
	this.hasThrown = false ;
	this.error = undefined ;
	this.return = undefined ;

	try {
		this.return = this.function.call( this.this || null , ... this.args ) ;
	}
	catch ( error ) {
		this.hasThrown = true ;
		this.error = error ;
	}

	if ( this.isAsync ) {
		if ( this.hasThrown ) {
			this.promise = Promise.resolve() ;
		}
		else {
			this.promise = Promise.resolve( this.return )
				.then(
					value => this.return = value ,
					error => {
						this.hasThrown = true ;
						this.error = error ;
					}
				) ;
		}
	}
}