Guest User

Untitled

a guest
May 26th, 2018
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.89 KB | None | 0 0
  1. local async = {}
  2.  
  3. --[[
  4. 时间原因,未考虑函数参数,返回结果及错误处理的情况
  5. ]]
  6. -- task(callback) callback是约定
  7.  
  8. function async.parallel(tasks)
  9. local len = #tasks
  10. if len < 1 then
  11. return
  12. end
  13.  
  14. for _, func in ipairs(tasks) do
  15. func()
  16. end
  17. end
  18.  
  19. function async.serial(tasks)
  20. local len = #tasks
  21. if len < 1 then
  22. return
  23. end
  24.  
  25. local index = 1
  26. local iterate
  27. iterate = function()
  28. local task = tasks[index]
  29. task(
  30. function ()
  31. index = index + 1
  32. if index <= len then
  33. iterate()
  34. end
  35. end
  36. )
  37. end
  38.  
  39. iterate()
  40. end
  41.  
  42. local function invoke_cb(cb)
  43. if nil ~= cb then
  44. cb()
  45. end
  46. end
  47.  
  48. -- 可以为异步函数
  49. local function func1(callback)
  50. invoke_cb(callback)
  51. print("func1")
  52. end
  53.  
  54. -- 可以为异步函数
  55. local function func2(callback)
  56. invoke_cb(callback)
  57. print("func2")
  58. end
  59.  
  60.  
  61. local my_tasks = {func1, func2}
  62.  
  63. async.serial(my_tasks)
  64. async.parallel(my_tasks)
Add Comment
Please, Sign In to add comment