-
Notifications
You must be signed in to change notification settings - Fork 0
/
promise.spec.lua
123 lines (107 loc) · 2.79 KB
/
promise.spec.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
mtt.register("simple promise", function(callback)
Promise.new(function(resolve)
resolve(5)
end):next(function(result)
assert(result == 5)
callback()
end)
end)
mtt.register("simple promise (resolved with false)", function(callback)
Promise.new(function(resolve)
resolve(false)
end):next(function(result)
assert(result == false)
callback()
end)
end)
mtt.register("simple promise (resolved with nil, chained with nil-result)", function(callback)
Promise.new(function(resolve)
resolve(nil)
end):next(function(result)
assert(result == nil)
end):next(function(result)
assert(result == nil)
return Promise.resolved()
end):next(function(result)
assert(result == nil)
callback()
end)
end)
mtt.register("returned promise", function(callback)
local p1 = Promise.new(function(resolve)
resolve(5)
end)
local p2 = Promise.new(function(resolve)
resolve(10)
end)
p1:next(function(result)
assert(result == 5)
return p2
end):next(function(result)
assert(result == 10)
callback()
end)
end)
mtt.register("error handling", function(callback)
Promise.new(function(_, reject)
reject("nope")
end):catch(function(err)
assert(err == "nope")
callback()
end)
end)
mtt.register("error handling 2", function(callback)
Promise.rejected("nope"):catch(function(err)
-- "nope"
assert(err)
end)
Promise.rejected("nope"):next(function() end):catch(function(err)
assert(err == "nope")
callback()
end)
end)
mtt.register("Promise.all", function(callback)
local p1 = Promise.new(function(resolve)
resolve(5)
end)
local p2 = Promise.new(function(resolve)
resolve(10)
end)
Promise.all(p1, p2):next(function(values)
assert(#values == 2)
assert(values[1] == 5)
assert(values[2] == 10)
callback()
end):catch(function(err)
callback(err)
end)
end)
mtt.register("Promise.race", function(callback)
local p1 = Promise.new(function(resolve)
resolve(5)
end)
local p2 = Promise.new()
Promise.race(p1, p2):next(function(v)
assert(v == 5)
callback()
end)
end)
mtt.register("Promise control logic", function(callback)
Promise.new(function(resolve)
resolve(math.random())
end):next(function(r)
if r < 0.5 then
-- branch 1
return Promise.new(function(resolve)
resolve(math.random())
end)
else
-- branch 2
return Promise.new(function(resolve)
resolve(math.random())
end)
end
end):next(function()
callback()
end)
end)