Skip to content

Commit a2c7992

Browse files
author
Rob Figueiredo
committed
Consolidate Then & Then2 by making Then variadic.
1 parent 3b3d215 commit a2c7992

File tree

2 files changed

+18
-16
lines changed

2 files changed

+18
-16
lines changed

promise.go

Lines changed: 17 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -86,29 +86,31 @@ func (p *Promise) Result() *Value {
8686
return val
8787
}
8888

89-
// Then invokes the given function when the promise has been fulfilled, not rejected.
90-
//
89+
// Then accepts 1 or 2 callbacks.
90+
// The first is invoked when the promise has been fulfilled.
91+
// The second is invoked when the promise has been rejected.
9192
// The returned Promise resolves after the callback finishes execution.
9293
//
9394
// V8 only invokes the callback when processing "microtasks".
9495
// The default MicrotaskPolicy processes them when the call depth decreases to 0.
9596
// Call (*Context).PerformMicrotaskCheckpoint to trigger it manually.
96-
func (p *Promise) Then(cb FunctionCallback) *Promise {
97+
func (p *Promise) Then(cbs ...FunctionCallback) *Promise {
9798
p.ctx.register()
9899
defer p.ctx.deregister()
99-
cbID := p.ctx.iso.registerCallback(cb)
100-
ptr := C.PromiseThen(p.ptr, C.int(cbID))
101-
return &Promise{&Object{&Value{ptr, p.ctx}}}
102-
}
103100

104-
// Then2 invokes one of the given functions when the promise is fulfilled or rejected.
105-
// See Then for other details.
106-
func (p *Promise) Then2(onFulfilled, onRejected FunctionCallback) *Promise {
107-
p.ctx.register()
108-
defer p.ctx.deregister()
109-
onFulfilledID := p.ctx.iso.registerCallback(onFulfilled)
110-
onRejectedID := p.ctx.iso.registerCallback(onRejected)
111-
ptr := C.PromiseThen2(p.ptr, C.int(onFulfilledID), C.int(onRejectedID))
101+
var ptr C.ValuePtr
102+
switch len(cbs) {
103+
case 1:
104+
cbID := p.ctx.iso.registerCallback(cbs[0])
105+
ptr = C.PromiseThen(p.ptr, C.int(cbID))
106+
case 2:
107+
cbID1 := p.ctx.iso.registerCallback(cbs[0])
108+
cbID2 := p.ctx.iso.registerCallback(cbs[1])
109+
ptr = C.PromiseThen2(p.ptr, C.int(cbID1), C.int(cbID2))
110+
111+
default:
112+
panic("1 or 2 callbacks required")
113+
}
112114
return &Promise{&Object{&Value{ptr, p.ctx}}}
113115
}
114116

promise_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,7 @@ func TestPromiseRejected(t *testing.T) {
7979
thenInfo = info
8080
return nil
8181
}).
82-
Then2(
82+
Then(
8383
func(_ *v8go.FunctionCallbackInfo) *v8go.Value {
8484
then2Fulfilled = true
8585
return nil

0 commit comments

Comments
 (0)