-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpromise.lua
62 lines (48 loc) · 1.35 KB
/
promise.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
local promise = {}
local successKey = "success"
promise.successKey = successKey
local failureKey = "failure"
promise.failureKey = failureKey
function promise.new()
local callbackTable = {}
local watchedPath = hs.execute("echo $RANDOM$RANDOM$RANDOM$RANDOM$RANDOM")
local state = hs.watchable.new(watchedPath)
hs.watchable.watch(
watchedPath, "*",
function(watchable, _path, key, _old, new)
local isSuccess = key == successKey
local isFailure = key == failureKey
if isSuccess or isFailure then
local onSuccess = callbackTable[successKey]
local onFailure = callbackTable[failureKey]
if isSuccess and callbackTable[successKey] then
onSuccess(new)
elseif isFailure and callbackTable[failureKey] then
onFailure(new)
end
watchable:release()
end
end
)
local _promise = {}
function _promise.onSuccess(onSuccess)
callbackTable[successKey] = onSuccess
end
function _promise.onFailure(onFailure)
callbackTable[failureKey] = onFailure
end
function _promise.succeed(value)
state[successKey] = value
end
function _promise.fail(value)
state[failureKey] = value
end
function _promise.success()
return state[successKey]
end
function _promise.failure()
return state[failureKey]
end
return _promise
end
return promise