-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add a
promises
package with a MakeHandledPromise
helper.
This helper function makes it convenient to create a promise in the context of k6 module/extension Go code.
- Loading branch information
Showing
1 changed file
with
46 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
// Package promises provides helpers for working with promises in k6. | ||
package promises | ||
|
||
import ( | ||
"github.com/dop251/goja" | ||
"go.k6.io/k6/js/modules" | ||
) | ||
|
||
// MakeHandledPromise can be used to create promises that will be dispatched to k6's event loop. | ||
// | ||
// Calling the function will create a goja promise and return its `resolve` and `reject` callbacks, wrapped | ||
// in such a way that it will block the k6 JS runtime's event loop from exiting before they are | ||
// called, even if the promise isn't revoled by the time the current script ends executing. | ||
// | ||
// A typical usage would be: | ||
// | ||
// func myAsynchronousFunc(vu modules.VU) *(goja.Promise) { | ||
// promise, resolve, reject := promises.MakeHandledPromise(vu) | ||
// go func() { | ||
// v, err := someAsyncFunc() | ||
// if err != nil { | ||
// reject(err) | ||
// return | ||
// } | ||
// | ||
// resolve(v) | ||
// }() | ||
// return promise | ||
// } | ||
func MakeHandledPromise(vu modules.VU) (*goja.Promise, func(interface{}), func(interface{})) { | ||
runtime := vu.Runtime() | ||
callback := vu.RegisterCallback() | ||
promise, resolve, reject := runtime.NewPromise() | ||
|
||
return promise, func(i interface{}) { | ||
callback(func() error { | ||
resolve(i) | ||
return nil | ||
}) | ||
}, func(i interface{}) { | ||
callback(func() error { | ||
reject(i) | ||
return nil | ||
}) | ||
} | ||
} |