Wraps asyncio.async()/asyncio.ensure_future() depending on the python version
    :param fut: The awaitable, future, or coroutine to wrap
    :param loop: The loop to run in
    :return: The wrapped future
501206
def ensure_future(fut, *, loop=None):
    
    if sys.version_info < (3, 4, 4):
        # This is to avoid a SyntaxError on 3.7.0a2+
        func = getattr(asyncio, "async")
    else:
        func = asyncio.ensure_future

    return func(fut, loop=loop)
437075
def sync_fetch(self, task):
        ''''''
        if not self._running:
            return self.ioloop.run_sync(functools.partial(self.async_fetch, task, lambda t, _, r: True))

        wait_result = threading.Condition()
        _result = {}

        def callback(type, task, result):
            wait_result.acquire()
            _result['type'] = type
            _result['task'] = task
            _result['result'] = result
            wait_result.notify()
            wait_result.release()

        wait_result.acquire()
        self.ioloop.add_callback(self.fetch, task, callback)
        while 'result' not in _result:
            wait_result.wait()
        wait_result.release()
        return _result['result']
1118032
def check_future(self, fut):
        """"""
        done = self.done = fut.done()
        if done and not self.prev_done:
            self.done_since = self.ioloop.time()
        self.prev_done = done
644189
def chain_future(a, b):
    
    def copy(future):
        assert future is a
        if b.done():
            return
        if (isinstance(a, TracebackFuture) and
                isinstance(b, TracebackFuture) and
                    a.exc_info() is not None):
            b.set_exc_info(a.exc_info())
        elif a.exception() is not None:
            b.set_exception(a.exception())
        else:
            b.set_result(a.result())
    a.add_done_callback(copy)
187137
def maybe_coroutine(obj):
    
    if six.PY3 and asyncio.iscoroutine(obj):
        return defer.ensureDeferred(obj)
    return obj
687398
def join(self):
        
        pending = set()
        exceptions = set()
        while len(self._tasks) > 0 or len(pending) > 0:
            while len(self._tasks) > 0 and len(pending) < self._concurrency:
                task, args, kwargs = self._tasks.pop(0)
                pending.add(task(*args, **kwargs))
            (done, pending) = yield from asyncio.wait(pending, return_when=asyncio.FIRST_COMPLETED)
            for task in done:
                if task.exception():
                    exceptions.add(task.exception())
        if len(exceptions) > 0:
            raise exceptions.pop()
597983
def coerce_to_synchronous(func):
    '''
    
    '''
    if inspect.iscoroutinefunction(func):
        @functools.wraps(func)
        def sync_wrapper(*args, **kwargs):
            loop = asyncio.get_event_loop()
            try:
                loop.run_until_complete(func(*args, **kwargs))
            finally:
                loop.close()
        return sync_wrapper
    return func
719801
def submit_future(self, func, *args, **kwargs):
        
        # This mode will run futures synchronously. This should only be used
        # for benchmarking purposes.
        if self.config["sync_http"] is True:
            return MockFuture(func, *args, **kwargs)

        future = self.pool.submit(func, *args, **kwargs)
        self.futures.append(future)
        return future
918291
def run_coroutine_threadsafe(coro, loop):
    
    if not asyncio.iscoroutine(coro):
        raise TypeError('A coroutine object is required')
    future = concurrent.futures.Future()

    def callback():
        try:
            _chain_future(asyncio.ensure_future(coro, loop=loop), future)
        except Exception as exc:
            if future.set_running_or_notify_cancel():
                future.set_exception(exc)
            raise

    loop.call_soon_threadsafe(callback)
    return future
1170950
def get_loop(self, *args, **kwargs):  # type: (typing.Any, typing.Any) -> asyncio.AbstractEventLoop
        """"""
        if callable(self.loop_getter):
            if self.loop_getter_need_context:
                return self.loop_getter(*args, **kwargs)  # pylint: disable=not-callable
            return self.loop_getter()  # pylint: disable=not-callable
        return self.loop_getter
413849
async def connect_async(self, loop=None, timeout=None):
        
        if self.deferred:
            raise Exception("Error, database not properly initialized "
                            "before opening connection")

        if self._async_conn:
            return
        elif self._async_wait:
            await self._async_wait
        else:
            self._loop = loop
            self._async_wait = asyncio.Future(loop=self._loop)

            conn = self._async_conn_cls(
                database=self.database,
                loop=self._loop,
                timeout=timeout,
                **self.connect_params_async)

            try:
                await conn.connect()
            except Exception as e:
                if not self._async_wait.done():
                    self._async_wait.set_exception(e)
                self._async_wait = None
                raise
            else:
                self._task_data = TaskLocals(loop=self._loop)
                self._async_conn = conn
                self._async_wait.set_result(True)
914736
async def _execute(self, fn, *args, **kwargs):
        """"""
        function = partial(fn, *args, **kwargs)
        future = self._loop.create_future()

        self._tx.put_nowait((future, function))

        return await future
1027299
def do_callback(self, pkt):
        
        callback, parser = self.get_callback_parser(pkt)

        if asyncio.iscoroutinefunction(callback):
            self.loop.call_soon_threadsafe(self._do_async_callback,
                                           callback, parser)
        else:
            self.loop.call_soon(callback, parser)
929628
def gather(self, futures, consume_exceptions=True):
        

        # from the asyncio docs: "If return_exceptions is True, exceptions
        # in the tasks are treated the same as successful results, and
        # gathered in the result list; otherwise, the first raised
        # exception will be immediately propagated to the returned
        # future."
        return asyncio.gather(*futures, return_exceptions=consume_exceptions)
545790
def _make_coroutine_wrapper(func, replace_callback):
    
    # On Python 3.5, set the coroutine flag on our generator, to allow it
    # to be used with 'await'.
    wrapped = func
    if hasattr(types, 'coroutine'):
        func = types.coroutine(func)

    @functools.wraps(wrapped)
    def wrapper(*args, **kwargs):
        future = TracebackFuture()

        if replace_callback and 'callback' in kwargs:
            callback = kwargs.pop('callback')
            IOLoop.current().add_future(
                future, lambda future: callback(future.result()))

        try:
            result = func(*args, **kwargs)
        except (Return, StopIteration) as e:
            result = _value_from_stopiteration(e)
        except Exception:
            future.set_exc_info(sys.exc_info())
            return future
        else:
            if isinstance(result, GeneratorType):
                # Inline the first iteration of Runner.run.  This lets us
                # avoid the cost of creating a Runner when the coroutine
                # never actually yields, which in turn allows us to
                # use "optional" coroutines in critical path code without
                # performance penalty for the synchronous case.
                try:
                    orig_stack_contexts = stack_context._state.contexts
                    yielded = next(result)
                    if stack_context._state.contexts is not orig_stack_contexts:
                        yielded = TracebackFuture()
                        yielded.set_exception(
                            stack_context.StackContextInconsistentError(
                                'stack_context inconsistency (probably caused '
                                'by yield within a "with StackContext" block)'))
                except (StopIteration, Return) as e:
                    future.set_result(_value_from_stopiteration(e))
                except Exception:
                    future.set_exc_info(sys.exc_info())
                else:
                    _futures_to_runners[future] = Runner(result, future, yielded)
                yielded = None
                try:
                    return future
                finally:
                    # Subtle memory optimization: if next() raised an exception,
                    # the future's exc_info contains a traceback which
                    # includes this stack frame.  This creates a cycle,
                    # which will be collected at the next full GC but has
                    # been shown to greatly increase memory usage of
                    # benchmarks (relative to the refcount-based scheme
                    # used in the absence of cycles).  We can avoid the
                    # cycle by clearing the local variable after we return it.
                    future = None
        future.set_result(result)
        return future

    wrapper.__wrapped__ = wrapped
    wrapper.__tornado_coroutine__ = True
    return wrapper
1029070
def _ensure_coroutine_function(func):
    
    if asyncio.iscoroutinefunction(func):
        return func
    else:
        @asyncio.coroutine
        def coroutine_function(evt):
            func(evt)
            yield
        return coroutine_function
935356
function async(func)
{
  function wrapper()
  {
    var context = this;
    var args    = arguments;
    process.nextTick(function()
    {
      func.apply(context, args);
    });
  }

  return wrapper;
}