-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
45 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,45 @@ | ||
// Package promises provides helpers for working with promises in k6. | ||
package promises | ||
|
||
import ( | ||
"github.com/dop251/goja" | ||
"go.k6.io/k6/js/modules" | ||
) | ||
|
||
// New 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 JavaScript runtime's event loop from exiting before they are | ||
// called, even if the promise isn't resolved by the time the current script ends executing. | ||
// | ||
// A typical usage would be: | ||
// | ||
// func myAsynchronousFunc(vu modules.VU) *(goja.Promise) { | ||
// promise, resolve, reject := promises.New(vu) | ||
// go func() { | ||
// v, err := someAsyncFunc() | ||
// if err != nil { | ||
// reject(err) | ||
// return | ||
// } | ||
// | ||
// resolve(v) | ||
// }() | ||
// return promise | ||
// } | ||
func New(vu modules.VU) (p *goja.Promise, resolve func(result any), reject func(reason any)) { | ||
p, resolve, reject = vu.Runtime().NewPromise() | ||
callback := vu.RegisterCallback() | ||
|
||
return p, func(i interface{}) { | ||
callback(func() error { | ||
resolve(i) | ||
return nil | ||
}) | ||
}, func(i interface{}) { | ||
callback(func() error { | ||
reject(i) | ||
return nil | ||
}) | ||
} | ||
} |