• Stars
    star
    216
  • Rank 183,179 (Top 4 %)
  • Language
    Lua
  • License
    MIT License
  • Created about 9 years ago
  • Updated almost 7 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A+ promises in Lua

lua-promises

Build Status

A+ promises in Lua

Why would I need promises?

Lua is normally single-threaded, so there is little need in asyncrhonous operations. However, if you use HTTP requests, or sockets, or other types of I/O - most likely your library would have asynchronous API:

readfile('file.txt', function(contents, err)
	if err then
		print('Error', err)
	else
		-- process file contents
	end
end)

Using callbacks like this can quickly become problematic (once you need to make multiple asyncrhonous actions depending on each other results). Let's imagine some protocol where we need to connect to the remote peer, perform some authentication, then send a request and finally receive some response:

connect(function(status, err)
	if err then .... end
	auth(function(token, err)
		if err then ... end
		request(token, function(res, err)
			if err then ... end
			handleresult(res)
		end)
	end)
end)

Here's how the code could be rewritten using promises API:

connect():next(function(status)
	return auth()
end):next(function(token)
	return request(token)
end):next(function(result)
	handleresult(res)
end, function(err)
	...handle error...
end)

This is cleaner and more readable, since it doesn't use lost of nested callbacks. Also it has a single place to handle all errors.

The idea is that each function return an object which can be later resolved or rejected. Various callbacks could be added to the object to get notified when the object is resolved. Such objects are called promises, deferred objects, thennables - all these names describe pretty much the same behavior.

Install

In terminal:

luarocks install --server=http://luarocks.org/dev lua-promises

In Lua code:

local deferred = require('deferred')

API

Create new promises:

  • d = deferred.new() - returns a new promise object d
  • d = deferred.all(promises) - returns a new promise object d that is resolved when all promises are resolved/rejected.
  • d = deferred.first(promises) - returns a new promise object d that is resolved as soon as the first of the promises gets resolved/rejected.
  • d = deferred.map(list, fn) - returns a new promise object d that is resolved with the values of sequential application of function fn to each element in the list. fn is expected to return promise object.

Resolve/reject:

  • d:resolve(value) - resolve promise object with value
  • d:reject(value) - reject promise object with value

Wait for the promise object:

  • d:next(cb, [errcb]) - enqueues resolve callback cb and (optionally) a rejection callback errcb. Resolve callback can be nil.

Example

local deferred = require('deferred')

--
-- Converting callback-based API into promise-based is very straightforward:
-- 
-- 1) Create promise object
-- 2) Start your asynchronous action
-- 3) Resolve promise object whenever action is finished (only first resolution
--    is accepted, others are ignored)
-- 4) Reject promise object whenever action is failed (only first rejection is
--    accepted, others are ignored)
-- 5) Return promise object letting calling side to add a chain of callbacks to
--    your asynchronous function

function read(f)
	local d = deferred.new()
	readasync(f, function(contents, err)
		if err == nil then
			d:resolve(contents)
		else
			d:reject(err)
		end
	end)
	return d
end

-- You can now use read() like this:
read('file.txt'):next(function(s)
	print('File.txt contents: ', s)
end, function(err)
	print('Error', err)
end)

Chaining promises

Promises can be chained (read A+ specs for more details). It's convenient when you need to do several asynchronous actions sequentially. Each callback can return another promise object, then further callbacks could wait for it to become resolved/rejected:

-- Reading two files sequentially:
read('first.txt'):next(function(s)
	print('File file:', s)
	return read('second.txt')
end):next(function(s)
	print('Second file:', s)
end):next(nil, function(err)
	-- error while reading first or second file
	print('Error', err)
end)

Processing lists

You can process a list of object asynchronously, so the next asynchronous action is started only when the previous one is successfully completed:

local items = {'a.txt', 'b.txt', 'c.txt'}
-- Read 3 files, one by one
deferred.map(items, read):next(function(files)
	-- here files is an array of file contents for each of the files
end, function(err)
	-- handle reading error
end)

Waiting for a group of promises

You may start multiple asynchronous actions in parallel and wait for all of them to complete:

deferred.all({
	http.get('http://example.com/first'),
	http.get('http://example.com/second'),
	http.get('http://example.com/third'),
}):next(function(results)
	-- handle results here (all requests are finished and there has been
	-- no errors)
end, function(results)
	-- handle errors here (all requests are finished and there has been
	-- at least one error)
end)

Waiting for the first promise

In some cases it's handy to wait for either of the promises. A good example is reading with timeout:

-- returns a promise that gets rejected after a certain timeout
function timeout(sec)
	local d = deferred.new()
	settimeout(function()
		d:reject('Timeout')
	end, sec)
	return d
end

deferred.first({
	read(somefile), -- resolves promise with contents, or rejects with error
	timeout(5),
}):next(function(result)
	...file was read successfully...
end, function(err)
	...either timeout or I/O error...
end)

License

Code is distributed under MIT license.

More Repositories

1

lorca

Build cross-platform modern desktop apps in Go + HTML5
Go
7,954
star
2

jsmn

Jsmn is a world fastest JSON parser/tokenizer. This is the official repo replacing the old one at Bitbucket
C
3,633
star
3

awfice

The world smallest office suite
HTML
3,462
star
4

fenster

The most minimal cross-platform GUI library
C++
513
star
5

tray

Cross-platform, super tiny C99 implementation of a system tray icon with a popup menu.
C
484
star
6

partcl

ParTcl - a micro Tcl implementation
C
467
star
7

metric

Minimal metrics for Go (counter/gauge/histogram). No dependencies. Compatible with expvar. Web UI included.
Go
353
star
8

luash

Tiny lua module to write shell scripts with lua (inspired by Python's sh module)
Lua
302
star
9

pt

Protothreads (coroutines) in C99. Highly portable, but work best in low-end embedded systems.
C
267
star
10

o

Tiny and simple React clone
JavaScript
249
star
11

log

Ultimately minimal (yet very convenient) logger for Android and Java
Java
157
star
12

tojvm

A toy JVM in Go
Go
156
star
13

webview-python

Python bindings to webview
Objective-C
151
star
14

bfapi

Resilient, scalable Brainf*ck, in the spirit of modern systems design
Go
144
star
15

nokia-composer

Nokia Composer in 512 bytes
HTML
125
star
16

expr

Fast and lightweight math expression evaluator in C99
C
119
star
17

hid

Simple HID driver for Go (pure golang, no dependencies, no cgo)
Go
119
star
18

zs

Absolutely minimal static site generator in Go (powers https://zserge.com)
Go
91
star
19

tinysh

Tiny UNIX shell, de-obfuscated, modernized, and "rewritten in Rust".
C
88
star
20

nanonn

A nano-framework for neural networks
Rust
83
star
21

dotfiles

git clone --bare https://github.com/zserge/dotfiles $HOME/.dotfiles && git --git-dir=$HOME/.dotfiles/ --work-tree=$HOME checkout
Vim Script
79
star
22

lc3-forth

Post-Apocalyptic Computing: bootstrapping Forth environment for LC-3 CPU
C
79
star
23

1bitr

Minimalistic text-based 1-bit music tracker
C
73
star
24

carnatus

A tiny chess engine in Go (sunfish port)
Go
65
star
25

odetoj

Rewrite of Arthur Whitney's one-page J interpreter in Rust
Rust
61
star
26

headline

Ascetic RSS reader in JavaScript, no server required
JavaScript
57
star
27

glob-grep

A little experiment: compare the languages aimed to replace C
Zig
52
star
28

buckbone

A simple android project generator for the Buck build system
Shell
52
star
29

q

Tiny and simple VueJS clone
JavaScript
46
star
30

beep

Cross-platform beep() function
C
43
star
31

slide

An attempt to implement Trikita Slide for desktop
C++
39
star
32

figma-simplify-path

Figma plugin to simplify vector paths
JavaScript
26
star
33

mucks

A tiny terminal session manager for Tmux, Screen and DVTM
Shell
20
star
34

anvil-kotlin-demos

Minimal tutorial/demos for Anvil+Kotlin
Kotlin
18
star
35

zserge.github.io

My static site
HTML
14
star
36

kv

An ultimately minimal persistent key-value store + LRU cache
Go
12
star
37

jsmn.lua

The world fastest JSON parser ported to Lua
Lua
11
star
38

aint

Code for the "AI or AIN'T" blog posts
Go
11
star
39

yu

Yu is a tee-like tool, but with rotation feature like logrotate
C
10
star
40

tab

🎼 A tiny CLI tool to render tabs for music instruments (🎹🎷🎺🎸🪕🪈 and many others!)
C
9
star
41

bsoz

One of the most minimal MOS6502 and retro computer emulators!
C
8
star
42

mdns

Very pragmatic mDNS implementation in Go
Go
8
star
43

kveer

A tiny in-memory key-value storage in Go with optional persistence (atomic backup file, or append-only)
Go
7
star
44

bf

Well, everyone has to write a brainf*ck interpreter at some point
C
7
star
45

covered

Trello Cover Card Generator
JavaScript
6
star
46

toy-java-agent

Toy Java agent
Java
6
star
47

atomicwriter

Atomic file writes in Go (using a unique temporary file and atomic rename)
Go
5
star
48

lex

A library for writing lexers in Go
Go
4
star
49

textizer

Minimal android widgets in Scheme
Java
4
star
50

chess

JavaScript
4
star
51

ping

An ultimately minimal social network, messaging, pub/sub and home automation app
4
star
52

tinylangs

Real programming langauges in 50 lines of code
Python
4
star
53

photo

Minimalistic private photo booth
HTML
3
star
54

incr

incr.it backend
JavaScript
3
star
55

zine

Tiny CSS template to produce micro-zines (folded 8-page magazines)
Python
3
star
56

one-click-hugo-cms

CSS
2
star
57

grafana-zero

Python
2
star
58

gif

Simple GIF recorder
HTML
2
star
59

protoc-gen-micro

Protobuf code generation for micro
Go
2
star
60

scaffold

Templates for quick project start
Java
1
star
61

r

Something that rhymes. Or not.
1
star