async

back.DEV

Известный
Автор темы
71
6
Версия MoonLoader
.026-beta
Привет
подскажите какой из этих способок асихронныв запросов лучше использовать и почему

ВАРИАНТ 1
Lua:
function async_http_request(method, url, args, resolve, reject) 
    local request_lane = lanes.gen('*', {package = {path = package.path, cpath = package.cpath}}, function()
        local ok, result = pcall(requests.request, method, url, args)
        if ok then
            result.json, result.xml = nil, nil -- cannot be passed through a lane
            return true, result
        else
            return false, result -- return error
        end
    end)
    if not reject then reject = function() end end
    lua_thread.create(function()
        local lh = request_lane()
        while true do
            local status = lh.status
            if status == 'done' then
                local ok, result = lh[1], lh[2]
                if ok then resolve(result) else reject(result) end
                return
            elseif status == 'error' then
                return reject(lh[1])
            elseif status == 'killed' or status == 'cancelled' then
                return reject(status)
            end
            wait(0)
        end
    end)
end

ВАРИАНТ 2
Lua:
function async_http_request(method, url, args, resolve, reject)
    if not _G["lanes.async_http"] then
        local linda = lanes.linda()
        local lane_gen = lanes.gen("*", {package = {path = package.path, cpath = package.cpath}}, function()
            local requests = require("requests")
            while true do
                local key, val = linda:receive(50 / 1000, "request")
                if key == "request" then
                    local ok, result = pcall(requests.request, val.method, val.url, val.args)
                    if ok then
                        result.json, result.xml = nil, nil
                        linda:send("response", result)
                    else linda:send("error", result) end
                end
            end
        end)
        _G["lanes.async_http"] = {lane = lane_gen(), linda = linda}
    end
    local lanes_http = _G["lanes.async_http"]
    lanes_http.linda:send("request", {method = method, url = url, args = args})
    lua_thread.create(function(linda)
        while true do
            local key, val = linda:receive(0, "response", "error")
            if key == "response" then return resolve(val)
            elseif key == "error" then return reject(val) end
            wait(0)
        end
    end, lanes_http.linda)
end