Skip to content

Commit

Permalink
Refactor promise helpers to fix Interrupt with async code
Browse files Browse the repository at this point in the history
This changes the promise helpers so after grafana/k6#4017 async code and
Interrupt will work.

AbortingPromises seems to have not been used at all and just adds
complexity. And `promises.New()` already does the remaining things
needed to happen, so this can be merged even without grafana/k6#4017.
  • Loading branch information
mstoykov committed Oct 25, 2024
1 parent 67d6dc8 commit f51aee9
Showing 1 changed file with 9 additions and 32 deletions.
41 changes: 9 additions & 32 deletions k6ext/promise.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,7 @@ import (
"context"

"github.com/grafana/sobek"
)

// eventLoopDirective determines whether the event
// loop should be aborted if the promise is rejected.
type eventLoopDirective int

const (
continueEventLoop eventLoopDirective = iota + 1
abortEventLoop
"go.k6.io/k6/js/promises"
)

// PromisifiedFunc is a type of the function to run as a promise.
Expand All @@ -23,33 +15,18 @@ type PromisifiedFunc func() (result any, reason error)
// first result value fn returns.
// - Otherwise, rejects the promise with the error fn returns.
func Promise(ctx context.Context, fn PromisifiedFunc) *sobek.Promise {
return promise(ctx, fn, continueEventLoop)
}

// AbortingPromise is like Promise, but it aborts the event loop if an error occurs.
func AbortingPromise(ctx context.Context, fn PromisifiedFunc) *sobek.Promise {
return promise(ctx, fn, abortEventLoop)
return promise(ctx, fn)
}

func promise(ctx context.Context, fn PromisifiedFunc, d eventLoopDirective) *sobek.Promise {
var (
vu = GetVU(ctx)
cb = vu.RegisterCallback()
p, resolve, reject = vu.Runtime().NewPromise()
)
func promise(ctx context.Context, fn PromisifiedFunc) *sobek.Promise {
p, resolve, reject := promises.New(GetVU(ctx))
go func() {
v, err := fn()
cb(func() error {
if err != nil {
reject(err)
} else {
resolve(v)
}
if d == continueEventLoop {
err = nil
}
return err
})
if err != nil {
reject(err)
return
}
resolve(v)
}()

return p
Expand Down

0 comments on commit f51aee9

Please sign in to comment.