A function decorated with this will always return a defer.Deferred
    even when returning synchronous result or raise an exception.
171403
def ensure_async(function_original):
    

    def wrapper(*args, **kwargs):
        try:
            result = function_original(*args, **kwargs)
            if isinstance(result, Deferred):
                return result
            d = Deferred()
            d.callback(result)
            return d
        except:
            return fail()

    return wrapper
695437
def wrap_async(func):
    """"""
    @functools.wraps(func)
    def wrapped(*args, **kwargs):
        fut = asyncio.ensure_future(func(*args, **kwargs))
        cur = greenlet.getcurrent()
        def callback(fut):
            try:
                cur.switch(fut.result())
            except BaseException as e:
                cur.throw(e)
        fut.add_done_callback(callback)
        return cur.parent.switch()
    return wrapped
124974
function wrapFunctionToReturnPromise(fn, Promise) {
	return function() {
		try {
			const result = fn.apply(this, arguments);
			if (result instanceof Promise) return result;
			return Promise.resolve(result);
		} catch (err) {
			return new Promise((resolve, reject) => { // jshint ignore:line
				reject(err);
			});
		}
	};
}
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)
           }
481875
function awaitFunction(fn) {
  return (req, res, next) => {
    Promise.resolve(fn(req, res, next)).catch(next);
  };
}
106869
function catchAsyncErrors(fn) {
	return 	async (...args) => {
				try{		await Promise.resolve(fn(...args)).catch(args[2])}
				catch(e){	args[2](e) }
			}
}
628892
function () {
	    	var deferred = $q.defer();
	    	var promise = deferred.promise;
            
            function ok(value){
                deferred.resolve(value);
            }
            
            function errorCallback(error){
                deferred.reject(new Error(error));
            }
            
            if($window.plugins){
                $window.plugins.appPreferences.show()
                    .then(ok, errorCallback);
            } else {
                deferred.reject(new Error(this.pluginNotEnabledMessage));
            }
	    	
	    	this.decoratePromise(promise);
	    	return promise;
	    }
791565
function async(callback)
{
  var isAsync = false;

  // check if async happened
  defer(function() { isAsync = true; });

  return function async_callback(err, result)
  {
    if (isAsync)
    {
      callback(err, result);
    }
    else
    {
      defer(function nextTick_callback()
      {
        callback(err, result);
      });
    }
  };
}
811185
def synced(func):
    '''
    
    '''

    def wrapper(self, *args, **kwargs):
        '''
        Actual wrapper for the synchronous function
        '''
        task = DataManagerTask(func, *args, **kwargs)
        self.submit_task(task)
        return task.get_results()
    return wrapper
954376
function defer(timeout) {
    var resolve, reject;
    var promise = new Promise(function() {
        resolve = arguments[0];
        reject = arguments[1];
        setTimeout(reject, timeout, "Timeout");
    });
    return {
        resolve: resolve,
        reject: reject,
        promise: promise,
        timestamp:new Date().getTime()
    };
}
105076
@Override
    public RequestPromise<T> always(io.reinert.gdeferred.AlwaysCallback<T, Throwable> callback) {
        super.always(callback);
        return this;
    }
367533
function (translationId) {
              var deferred = $q.defer();
              var regardless = function (value) {
                results[translationId] = value;
                deferred.resolve([translationId, value]);
              };
              // we don't care whether the promise was resolved or rejected; just store the values
              $translate(translationId, interpolateParams, interpolationId, defaultTranslationText).then(regardless, regardless);
              return deferred.promise;
            }
500345
function deferred(mediaObject, params, prevRpc, callback) {
  var promises = [];

  if (mediaObject != undefined)
    promises.push(mediaObject);

  for (var key in params) {
    var param = params[key];
    if (param !== undefined)
      promises.push(param);
  };

  if (prevRpc != undefined)
    promises.push(prevRpc);

  return promiseCallback(Promise.all(promises), callback);
}
1353979
function (i) {
        var deferred = $.Deferred();
        deferreds.push(deferred);

        var originalVal = changes[i][3];
        var lowercaseVal = typeof originalVal === 'string' ? originalVal.toLowerCase() : null;

        return function (source) {
          var found = false;
          for (var s = 0, slen = source.length; s < slen; s++) {
            if (originalVal === source[s]) {
              found = true; //perfect match
              break;
            }
            else if (lowercaseVal === source[s].toLowerCase()) {
              changes[i][3] = source[s]; //good match, fix the case
              found = true;
              break;
            }
          }
          if (!found) {
            changes[i] = null;
          }
          deferred.resolve();
        }
      }
473778
function(deferred, message) {
			var that = this;
			if(message){
				that.setProgressMessage(message);
				var finish = function(){
					if(message === that.progressMessage){
						that.setProgressMessage("");
					}
				};
				deferred.then(finish, finish);
			}
			return deferred;
		}
80362
def _runDeferredFunctions(deferredFunctions):
        
        failures = []
        for deferredFunction in deferredFunctions:
            try:
                deferredFunction.invoke()
            except:
                failures.append(deferredFunction.name)
                logger.exception('%s failed.', deferredFunction)
        return failures
214159
function () {

    var after = {
        loop: function (condition) {
            if (!utils.isFunction(condition)) {
                throw new Error('Asynk loop function require a function as first argument');
            }
            _Context.loopDefer = _Context.loopDefer || new Deferred();
            _Context.loopResults = _Context.loopResults || [];
            this.done(function () {
                var result = utils.toArray(arguments);
                if (result.length > 1) {

                    _Context.loopResults.push(result);
                }
                else {
                    _Context.loopResults.push(result[0]);
                }

                if (condition.apply(null, result)) {
                    //reset values
                    for (var i in _Context.tasks) {
                        _Context.tasks[i].status = WAITING;
                    }
                    _Context.results = [];
                    _Context.currentTasks = [];
                    _Context.exec.fct.apply(null, _Context.exec.args).loop(condition);
                }
                else {
                    _Context.loopDefer.resolve(_Context.loopResults);
                }
            });
            this.fail(_Context.loopDefer.reject);
            return _Context.loopDefer.promise();
        },
        asyncLoop: function (condition) {
            if (!utils.isFunction(condition)) {
                throw new Error('Asynk loop function require a function as first argument');
            }
            _Context.loopDefer = _Context.loopDefer || new Deferred();
            _Context.loopResults = _Context.loopResults || [];
            this.done(function () {
                var result;
                if (arguments.length > 1) {
                    result = utils.toArray(arguments);
                }
                else {
                    result = arguments[0];
                }
                _Context.loopResults.push(result);
                
                condition.apply(null, [result, function (err, loop) {
                    if (err) {
                        return _Context.loopDefer.reject(err);
                    }
                    if (loop) {
                        //reset values
                        for (var i in _Context.tasks) {
                            _Context.tasks[i].status = WAITING;
                        }
                        _Context.results = [];
                        _Context.currentTasks = [];
                        _Context.exec.fct.apply(null, _Context.exec.args).asyncLoop(condition);
                    }
                    else {
                        _Context.loopDefer.resolve(_Context.loopResults);
                    }
                }]);
            });
            this.fail(_Context.loopDefer.reject);
            return _Context.loopDefer.promise();
        }
    };

    var Asynk = {};

    var _Context = {
        tasks: [],
        aliasMap: {},
        results: [],
        currentTasks: Asynk.currentTasks
    };

    Asynk.add = function (fct) {
        if (utils.isUndefined(fct) || !utils.isFunction(fct)) {
            throw new Error('Asynk add require a function as argument');
        }
        var newId = _Context.tasks.length;
        _Context.tasks[newId] = new Task(_Context, newId, fct);
        _Context.currentTasks = [newId];
        this.args(new DefArg('callback'));
        return this;
    };

    Asynk.each = function (datas, fct) {
        if (utils.isUndefined(fct) || !utils.isFunction(fct)) {
            throw new Error('Asynk each require a function as second argument');
        }
        _Context.currentTasks = [];
        datas.forEach(function (data) {
            var newId = _Context.tasks.length;
            _Context.tasks[newId] = new Task(_Context, newId, fct);
            _Context.tasks[newId].item = data;
            _Context.currentTasks.push(newId);
        });
        this.args(new DefArg('item'), new DefArg('callback'));
        return this;
    };

    Asynk.args = function () {
        var args = utils.toArray(arguments);
        _Context.currentTasks.forEach(function(currentTask) {
            _Context.tasks[currentTask].args = utils.toArray(args);
        });
        return this;
    };

    Asynk.require = function (dependencies) {
        if (!utils.isArray(dependencies)) {
          dependencies = [dependencies];
        }
        _Context.currentTasks.forEach(function(currentTask) {
            var current = _Context.tasks[currentTask];
            current.dependencies = current.dependencies.concat(dependencies);
        });
        return this;
    };

    Asynk.alias = function (alias) {
        if (utils.isString(alias)) {
            _Context.currentTasks.forEach(function (currentTask, index) {
                _Context.tasks[currentTask].alias = alias;
            });
            if (_Context.currentTasks.length > 1) {
                _Context.aliasMap[alias] = _Context.currentTasks;
            }
            else {
                _Context.aliasMap[alias] = _Context.currentTasks[0];
            }
        }
        return this;
    };

    Asynk.serie = function(endcallArgs) {
        _Context.exec = {
            fct: Asynk.serie,
            args: [endcallArgs]
        };
        var defer = new Deferred();
        var endTask = new Task(_Context, 'end', defer.resolve.bind(defer));
        endTask.args = endcallArgs || [new DefArg('alias', 'all')];
        var currentId = 0;

        var cb = function (err, data) {
            if (err) {
                _Context.tasks[currentId].status = FAIL;
                defer.reject(err);
                endTask.reject(err);
                return;
            }
            _Context.tasks[currentId].status = DONE;
            _Context.results.push(data);
            currentId++;
            next();
        };
        var next = function() {
            var current = _Context.tasks[currentId];
            if (current) {
                current.setCallback(cb);
                current.execute();
                if (current.status === WAITING_FOR_DEPENDENCY) {
                    defer.reject(new Error('could not resolve this dependancies'));
                }
            }
            else {
                endTask.execute();
            }
        };
        next();
        return defer.promise(after);
    };

    Asynk.parallel = function(endcallArgs) {
        _Context.exec = {
            fct: Asynk.parallel,
            args: [endcallArgs]
        };
        var defer = new Deferred();
        var endTask = new Task(_Context, 'end', defer.resolve.bind(defer));
        endTask.args = endcallArgs || [new DefArg('alias', 'all')];

        var count = 0;
        var todo = _Context.tasks.length;
        var cb = function (task, err, data) {
            task.status = DONE;
            if (err) {
                defer.reject(err);
                endTask.reject(err);
                return;
            }
            _Context.results[task.id] = data;
            count++;
            if (count >= todo) {
                endTask.execute();
            }
            else {
                _Context.tasks.forEach(function(task) {
                    if (task.status === WAITING_FOR_DEPENDENCY) {
                        task.execute();
                    }
                });
            }
        };

        if (_Context.tasks.length === 0) {
            endTask.execute();
            return defer.promise();
        }

        _Context.tasks.forEach(function(task) {
            task.setCallback(function (err, data) {
                cb(task, err, data);
            });
        });

        _Context.tasks.forEach(function(task) {
            task.execute();
        });

        return defer.promise(after);
    };

    Asynk.parallelLimited = function(limit, endcallArgs) {
        _Context.exec = {
            fct: Asynk.parallelLimited,
            args: [limit, endcallArgs]
        };
        var defer = new Deferred();
        var endTask = new Task(_Context, 'end', defer.resolve.bind(defer));
        endTask.args = endcallArgs || [new DefArg('alias', 'all')];

        var count = 0;
        var todo = _Context.tasks.length;
        var cb = function (task, err, data) {
            task.status = DONE;
            if (err) {
                defer.reject(err);
                endTask.reject(err);
                return;
            }
            _Context.results[task.id] = data;
            count++;
            if (count >= todo) {
                endTask.execute();
            }
            else {
                _Context.tasks.forEach(function(task) {
                    var stats = utils.countBy(_Context.tasks, function(task) {
                        return task.status;
                    });
                    var running = stats[RUNNING] || 0;
                    if ((running < limit) && (task.status < RUNNING)) {
                        task.execute();
                    }
                });
            }
        };

        if (_Context.tasks.length === 0) {
            endTask.execute();
            return defer.promise();
        }

        _Context.tasks.forEach(function(task) {
            task.setCallback(function (err, data) {
                cb(task, err, data);
            });
        });

        _Context.tasks.forEach(function(task) {
            var stats = utils.countBy(_Context.tasks, function(task) {
                return task.status;
            });
            var running = stats[RUNNING] || 0;
            if ((running < limit) && (task.status < RUNNING)) {
                task.execute();
            }
        });

        return defer.promise(after);
    };

    return Asynk;
}