异步写入，通过 asyncio 的原生异步
343122
def write(self, data: bytes, sync: bool = False) -> None:
        
        if sync:
            self.sync_write(data)
        else:
            self._transport.write(data)
1292483
async def _write_loop(self):
        
        while self.state == 'connected':
            # to simplify the timeout handling, use the maximum of the
            # ping interval and ping timeout as timeout, with an extra 5
            # seconds grace period
            timeout = max(self.ping_interval, self.ping_timeout) + 5
            packets = None
            try:
                packets = [await asyncio.wait_for(self.queue.get(), timeout)]
            except (self.queue.Empty, asyncio.TimeoutError,
                    asyncio.CancelledError):
                self.logger.error('packet queue is empty, aborting')
                self._reset()
                break
            if packets == [None]:
                self.queue.task_done()
                packets = []
            else:
                while True:
                    try:
                        packets.append(self.queue.get_nowait())
                    except self.queue.Empty:
                        break
                    if packets[-1] is None:
                        packets = packets[:-1]
                        self.queue.task_done()
                        break
            if not packets:
                # empty packet list returned -> connection closed
                break
            if self.current_transport == 'polling':
                p = payload.Payload(packets=packets)
                r = await self._send_request(
                    'POST', self.base_url, body=p.encode(),
                    headers={'Content-Type': 'application/octet-stream'})
                for pkt in packets:
                    self.queue.task_done()
                if r is None:
                    self.logger.warning(
                        'Connection refused by the server, aborting')
                    break
                if r.status != 200:
                    self.logger.warning('Unexpected status code %s in server '
                                        'response, aborting', r.status)
                    self._reset()
                    break
            else:
                # websocket
                try:
                    for pkt in packets:
                        await self.ws.send(pkt.encode(always_bytes=False))
                        self.queue.task_done()
                except websockets.exceptions.ConnectionClosed:
                    self.logger.info(
                        'Write loop: WebSocket connection was closed, '
                        'aborting')
                    break
        self.logger.info('Exiting write loop task')
1048637
def next(self, *args):
        """"""
        self.initialize()
        self.future = asyncio.Future(loop=self.loop)
        self.handle = self.loop.call_at(self.get_next(), self.call_func, *args)
        return self.future
1343783
async def stderr(self) -> AsyncGenerator[str, None]:
        """"""
        await self.wait_running()
        async for line in self._subprocess.stderr:  # type: ignore
            yield line
19607
def threadpooled(
    func: typing.Callable[..., typing.Union["typing.Awaitable[typing.Any]", typing.Any]],
    *,
    loop_getter: typing.Union[typing.Callable[..., asyncio.AbstractEventLoop], asyncio.AbstractEventLoop],
    loop_getter_need_context: bool = False,
) -> typing.Callable[..., "asyncio.Task[typing.Any]"]:
    """"""
70256
def coroutine(func):
    
    def wrapper(*args, **kwargs):
        gen = func(*args, **kwargs)
        val = next(gen)
        if val != None:
            raise TypeError('Unexpected value from start of coroutine')
        return gen
    wrapper.__name__ = func.__name__
    wrapper.__doc__ = func.__doc__
    return wrapper
371541
function () {

    var keys = Object.keys(wating);

    /*
     * 检测依赖关系，
     * FIXME 暂时未处理循环依赖.以及始终不满足执行条件的情况.
     */
    keys.forEach(function (name) {
        var args = [];
        var factory = wating[name][0];
        var depends = wating[name][1];
        var done = wating[name][2];

        var canDo = depends.every(function (name) {

            // 插件系统中内容优先，资源池中置后
            var value = working[name] || Resource[name];

            if (value) {
                args.push(value);
                return true;
            }

            return false;
        });

        if (canDo) {
            // 先移除，防止callback中检测依赖时产生的循环
            delete wating[name];

            //  判断异步及同步
            if (done) {
                args.push(done);
                factory.apply( {}, args);
            } else {
                try {
                    var value = working[name] = factory.apply( {}, args);

                    oldDefineOfPlugin.call(Plugin, name, value);
                }catch(err) {
                    stdLog(['%s, can not start the plug-in [%s], \nstack:', err.stack, name], 'crash');
                    process.exit(0);
                    return;
                }
            }
        }
    });
}
1126144
function compose(middlewares, ctx) {
    let i = middlewares.length;
    let next = async function(){};

    // 循环算出来next
    for (let i = middlewares.length - 1; i >=0; i--) {
        next = getCallback(middlewares[i], ctx, next);
    }

    return next;
}
899889
function TransmitOralProcess(client, req) {
    return new Promise(function (resolve, reject) {
        // 通过client对象调用想要访问的接口，需要传入请求对象以及响应回调函数
        client.TransmitOralProcess(req, function (err, response) {
            if (err) {
                reject(err)
                return;
            }
            // 请求正常返回，打印response对象
            resolve(response)
        });
    })
}
999756
def create_future(loop):
    # pragma: no cover
    """"""
    if hasattr(loop, 'create_future'):
        return loop.create_future()
    return asyncio.Future(loop=loop)
196987
def _asynciostacks(*args, **kwargs):  # pragma: no cover
    '''
    
    '''
    print(80 * '*')
    print('Asyncio tasks stacks:')
    tasks = asyncio.all_tasks(_glob_loop)
    for task in tasks:
        task.print_stack()
    print(80 * '*')
    print('Faulthandler stack frames per thread:')
    faulthandler.dump_traceback()
    print(80 * '*')
715310
async def async_init(self):
        
        self.session = aiohttp.ClientSession()
        asyncio.get_event_loop().create_task(self._deferred_init())
413094
async def main():
    """"""
    for c in (1, 2, 4,):
        async with Sublemon(max_concurrency=c) as s:
            start = time.perf_counter()
            await asyncio.gather(one(s), two(s))
            end = time.perf_counter()
            print('Limiting to', c, 'concurrent subprocess(es) took',
                  end-start, 'seconds\n')
820557
def _run_asyncio(loop, zmq_context):
    
    try:
        asyncio.set_event_loop(loop)
        loop.run_forever()
    except:
        pass
    finally:
        loop.close()
        zmq_context.destroy(1000)
938306
async function(program) {
        let filesToParse = [];
        let folderStat = '';
        if(program.in) {
            filesToParse.push(program.in);
        }
        // do we have a folder passed in?
        if(program.lu_folder) {
            try
            {
                folderStat = fs.statSync(program.lu_folder);
            } catch (err) {
                throw(new exception(retCode.errorCode.OUTPUT_FOLDER_INVALID, 'Sorry, ' + program.lu_folder + ' is not a folder or does not exist'));
            }
            if(!folderStat.isDirectory()) {
                throw(new exception(retCode.errorCode.OUTPUT_FOLDER_INVALID, 'Sorry, ' + program.lu_folder + ' is not a folder or does not exist'));
            }
            if(program.subfolder) {
                filesToParse = helpers.findLUFiles(program.lu_folder, true); 
            } else {
                filesToParse = helpers.findLUFiles(program.lu_folder, false); 
            }
            if(filesToParse.length === 0) {
                throw(new exception(retCode.errorCode.NO_LU_FILES_FOUND, 'Sorry, no .lu files found in the specified folder.'));
            }
        }
        // is there an output folder?
        let outFolder = process.cwd();
        if(program.out_folder) {
            if(path.isAbsolute(program.out_folder)) {
                outFolder = program.out_folder;
            } else {
                outFolder = path.resolve('', program.out_folder);
            }
            if(!fs.existsSync(outFolder)) {
                throw(new exception(retCode.errorCode.OUTPUT_FOLDER_INVALID, 'Output folder ' + outFolder + ' does not exist'));
            }
        }
        while(filesToParse.length > 0) {
            let file = filesToParse[0];
            try {
                await parseFile(file, outFolder, program.translate_key, program.to_lang, program.src_lang, program.translate_comments, program.translate_link_text, program.verbose, program.batch_translate);
            } catch (err) {
                throw(err);
            }
            filesToParse.splice(0,1);
         }
    }
395211
def AsyncResponseMiddleware(environ, resp):
    '''
    '''
    future = create_future()
    future._loop.call_soon(future.set_result, resp)
    return future
1024102
def runcoro(async_function):
    

    future = _asyncio.run_coroutine_threadsafe(async_function, client.loop)
    result = future.result()
    return result