Skip to content

Commit 02b64af

Browse files
committed
new() allows to start a chain of promises with a function taking a promise
1 parent a67a159 commit 02b64af

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed

deferred.lua

+8
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,14 @@ function deferred:reject(value)
120120
end
121121

122122
function M.new(options)
123+
if isfunction(options) then
124+
local d = M.new()
125+
local ok, err = pcall(options, d)
126+
if not ok then
127+
d:reject(err)
128+
end
129+
return d
130+
end
123131
options = options or {}
124132
local d
125133
d = {

deferred_test.lua

+17
Original file line numberDiff line numberDiff line change
@@ -352,4 +352,21 @@ test('Race of rejected promises', function()
352352
ok(g.called[1][1] == 'foo', 'promise was rejected with the first error')
353353
end)
354354

355+
test('Passing a function into new(): resolve', function()
356+
local f = spy(function(d) d:resolve(42) end)
357+
local g = spy()
358+
deferred.new(f):next(g)
359+
ok(#f.called == 1, 'first callback in chain called once')
360+
ok(g.called[1][1] == 42, 'second callback received deferred value')
361+
end)
362+
363+
test('Passing a function into new(): reject', function()
364+
local f = function(d) error('panic', 0) end
365+
local g = spy()
366+
local e = spy()
367+
deferred.new(f):next(g, e)
368+
ok(not g.called, 'resolve handler was not called')
369+
ok(e.called[1][1] == 'panic', 'error handler was called')
370+
end)
371+
355372
if tests_failed > 0 then os.exit(1) end

0 commit comments

Comments
 (0)