From f51aee90a44ead038cee98dc3f59aa66faafd97d Mon Sep 17 00:00:00 2001 From: Mihail Stoykov Date: Fri, 25 Oct 2024 11:07:56 +0300 Subject: [PATCH] Refactor promise helpers to fix Interrupt with async code 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. --- k6ext/promise.go | 41 +++++++++-------------------------------- 1 file changed, 9 insertions(+), 32 deletions(-) diff --git a/k6ext/promise.go b/k6ext/promise.go index 5aca02218..19fb80a35 100644 --- a/k6ext/promise.go +++ b/k6ext/promise.go @@ -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. @@ -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