Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor promise helpers to fix Interrupt with async code #1498

Merged
merged 1 commit into from
Oct 25, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading