在lua里面的异步代码主要是通过闭包实现,结合asio,一些简单的封装,方便编写异步代码,比如异步的while,异步的for等

useage:

1--[[ 2* Author: caoshanshan 3* Email: me@dreamyouxi.com 4异步lib 封装 方便快速写异步lua代码 5@see useage 6]] 7 8local t = { } 9 10-- 异步循环调用 直到成功 或者达到深度 11-- cb需要执行的函数 第一个参数是async对象,调用async:_continue() 继续执行 12-- auto_run run auto ? if not you should call it manual 13-- max run depth ,just for avoid run forever 14function t.async_while_true(cb, auto_run, MAX_DEPTH) 15 local depth = 0; 16 if auto_run == nil then 17 auto_run = true; 18 end 19 MAX_DEPTH = MAX_DEPTH or 1000; 20 local obj = { }; 21 obj.run = true; 22 obj.cb = cb; 23 obj._continue = function(self) 24 if self.run and depth < MAX_DEPTH then 25 depth = depth + 1; 26 self:cb(); 27 else 28 -- print(" out of range"); 29 end 30 end 31 obj._break = function(self) 32 self.run = false; 33 end 34 if auto_run then 35 obj:_continue(); 36 end 37 return obj; 38end 39 40 41return t; 42 43 44useage: 45 46 47function t.ttttt(ctx, msg, cb) 48 local redis_key = redis_key.get_uuid_gen(); 49 50 async.async_while_true( function(async) 51 redis.incr(redis_key, function(v) 52 if v and v ~= "" then 53 local ok = uuid_helper.check_is_valid(v); 54 if ok then 55 local uuid = v; 56 cb(uuid); 57 else 58 -- re gen 59 async:_continue(); 60 return; 61 end 62 end 63 end ) 64 end ); 65end