Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function asyncHttpRequest(method, url, args, resolve, reject)
- assert(type(method) == 'string', '"method" expected string')
- assert(type(url) == 'string', '"url" expected string')
- assert(type(args) == 'table', '"args" expected table')
- local thread = requestRunner()(method, url, effil.table(args))
- if not resolve then resolve = function() end end
- if not reject then reject = function() end end
- return {
- effilRequestThread = thread;
- luaHttpHandleThread = lua_thread.create(handleAsyncHttpRequestThread, thread, resolve, reject);
- }
- end
- function handleAsyncHttpRequestThread(runner, resolve, reject)
- local status, err
- repeat
- status, err = runner:status()
- wait(0)
- until status ~= 'running'
- if not err then
- if status == 'completed' then
- local result, response = runner:get()
- if result then
- resolve(response)
- else
- reject(response)
- end
- return
- elseif status == 'canceled' then
- return reject(status)
- end
- else
- return reject(err)
- end
- end
- function requestRunner()
- return effil.thread(function(method, url, args)
- local requests = require 'requests'
- local _args = {}
- local function table_assign(target, def, deep)
- for k, v in pairs(def) do
- if target[k] == nil then
- if type(v) == 'table' or type(v) == 'userdata' then
- target[k] = {}
- table_assign(target[k], v)
- else
- target[k] = v
- end
- elseif deep and (type(v) == 'table' or type(v) == 'userdata') and (type(target[k]) == 'table' or type(target[k]) == 'userdata') then
- table_assign(target[k], v, deep)
- end
- end
- return target
- end
- table_assign(_args, args, true)
- local result, response = pcall(requests.request, method, url, _args)
- if result then
- response.json, response.xml = nil, nil
- return true, response
- else
- return false, response
- end
- end)
- end
Advertisement
Advertisement