Skip to content

BlakeLiAFK/async.lua

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

21 Commits
 
 
 
 
 
 
 
 

Repository files navigation

async.lua

为什么要用async.lua (why you need async.lua)

你可以使用async.lua来管理回调函数, 避免在callback hell里沉沦, 减少心智负担.

You can use async.lua to manage your callback functions, avoid sinking in callback hell, and reduce mental burden.

API

async.waterfall(tasks, callback)

瀑布流执行 - 按顺序执行任务,每个任务的结果会传递给下一个任务。

参数:

  • tasks (array): 函数数组,每个函数接收 (callback, ...) 参数
  • callback (function): 最终回调函数 function(err, result)

示例:

async.waterfall({
    function (callback)
        callback(nil, 1, 2)
    end,
    function (callback, a, b)
        print(a, b)  -- 输出: 1, 2
        callback(nil, 3)
    end,
    function(callback, a)
        print(a)  -- 输出: 3
        callback(nil, 4)
    end
},
function (err, result)
    if err then
        print('error:', err)
    else
        print(result)  -- 输出: 4
    end
end)

async.parallel([max_parallel_num,] tasks, callback)

并行执行任务,可选择性地限制最大并行数量。

参数:

  • max_parallel_num (number, 可选): 最大并行数量,默认为 5
  • tasks (array): 函数数组,每个函数接收 (callback) 参数
  • callback (function): 最终回调函数 function(err, results)

返回值:

  • results 是一个数组,每个元素是对应任务的返回值数组

示例 1 - 默认并行数:

async.parallel({
    function (callback)
        callback(nil, 'task1')
    end,
    function (callback)
        callback(nil, 'task2')
    end,
    function (callback)
        callback(nil, 'task3')
    end
},
function (err, results)
    if err then
        print('error:', err)
    else
        -- results = {{'task1'}, {'task2'}, {'task3'}}
        for i, result in ipairs(results) do
            print(result[1])
        end
    end
end)

示例 2 - 指定最大并行数:

-- 最多同时执行 2 个任务
async.parallel(2, {
    function (callback)
        callback(nil, 'A')
    end,
    function (callback)
        callback(nil, 'B')
    end,
    function (callback)
        callback(nil, 'C')
    end,
    function (callback)
        callback(nil, 'D')
    end
},
function (err, results)
    if err then
        print('error:', err)
    else
        print('all tasks completed')
    end
end)

注意:

  • 当任务数量超过 max_parallel_num 时,任务会被分组,每组最多 max_parallel_num 个任务,各组按顺序执行
  • 如果任何一个任务返回错误,整个操作会立即终止并调用最终回调

错误处理

所有回调函数的第一个参数都是错误对象 err

  • 如果没有错误,err 应该为 nil
  • 如果有错误,传递错误信息(通常是字符串)
-- 错误示例
async.waterfall({
    function (callback)
        callback('something went wrong')
    end,
    function (callback)
        -- 这个函数不会被执行
        callback(nil, 'result')
    end
},
function (err, result)
    if err then
        print('error occurred:', err)  -- 输出: error occurred: something went wrong
    end
end)

运行测试

lua test.lua

About

lua async call

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 2

  •  
  •  

Languages