Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/lewis6991/async.nvim
Small aync library for Neovim plugins
https://github.com/lewis6991/async.nvim
lua lua-library neovim neovim-plugin
Last synced: 21 days ago
JSON representation
Small aync library for Neovim plugins
- Host: GitHub
- URL: https://github.com/lewis6991/async.nvim
- Owner: lewis6991
- License: mit
- Created: 2022-09-13T17:37:48.000Z (about 2 years ago)
- Default Branch: main
- Last Pushed: 2024-07-14T13:44:11.000Z (4 months ago)
- Last Synced: 2024-10-10T23:25:55.022Z (about 1 month ago)
- Topics: lua, lua-library, neovim, neovim-plugin
- Language: Lua
- Homepage:
- Size: 8.79 KB
- Stars: 43
- Watchers: 4
- Forks: 2
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# async.nvim
Small async library for Neovim plugins## Example
Take the current function that uses a callback style function to run a system process.
```lua
local function run_job(cmd, args, callback)
local handle
handle = vim.uv.spawn(cmd, { args = args, },
function(code)
s.handle:close()
callback(code)
end
)
end
```If we want to emulate something like:
```lua
echo foo && echo bar && echo baz
```Would need to be implemented as:
```lua
run_job('echo', {'foo'},
function(code1)
if code1 ~= 0 then
return
end
run_job('echo', {'bar'},
function(code2)
if code2 ~= 0 then
return
end
run_job('echo', {'baz'})
end
)
end
)```
As you can see, this quickly gets unwieldy the more jobs we want to run.
`async.nvim` simplifies this significantly.
First we turn this into an async function using `wrap`:
```lua
local a = require('async')
local run_job_a = a.wrap(3, run_job)
```Now we need to create a top level function to initialize the async context. To do this we can use `void` or `sync`.
Note: the main difference between `void` and `sync` is that `sync` functions can be called with a callback (like the `run_job` in a non-async context, however the user must provide the number of agurments.
For this example we will use `void`:
```lua
local main = a.sync(0, function()
local code1 = run_job_a('echo', {'foo'})
if code1 ~= 0 then
return
endlocal code2 = run_job_a('echo', {'bar'})
if code2 ~= 0 then
return
endrun_job_a('echo', {'baz'})
end)main()
```We can now call `run_job_a` in linear imperative fashion without needing to define callbacks.
The arguments provided to the callback in the original function are simply returned by the async version.