nvim-neotest / nvim-nio

A library for asynchronous IO in Neovim
MIT License
305 stars 9 forks source link

[Proposal] Convenient one-shot async call of function #20

Open yioneko opened 5 months ago

yioneko commented 5 months ago

I don't know if this type of API was ever been considered, but I'd like to see this form of async call API:

local nio = require("nio")
local function func_with_cb(arg1, arg2, cb)
  -- ....
end
-- currently, to call one function asynchronously, we have to firstly `nio.wrap` it:
local async_func = nio.wrap(func_with_cb, 2)
local ret = async_func(arg1, arg2)

-- while how about we have this form of one-shot call API:
local ret = nio.call(func_with_cb, arg1, arg2)
-- In this form, not only we do not need to wrap it first, but also there is
-- no assumption on the argc of function, and we do not need to count
-- argc manually

-- The API could be defined as simple as follows:
function nio.call(func, ...)
  local argc = select("#", ...) + 1
  local args = { ... }
  local ret = { coroutine.yield(argc, func, ...) }
  return unpack(ret, 2, table.maxn(ret))
end

Also I wonder if it is possible to make argc optional in nio.wrap by using debug.getinfo(func, "u").nparams.

EDIT: My attempt to implement these: https://github.com/yioneko/nvim-nio/commit/f0570666918d075a276daf755ee90b4ed5c33c76