Skip to content

Commit

Permalink
Add a promises package with a MakeHandledPromise helper.
Browse files Browse the repository at this point in the history
This helper function makes it convenient to create a promise in the
context of  k6 module/extension Go code.
  • Loading branch information
oleiade committed Jul 7, 2023
1 parent a2fe0a8 commit 606d2ee
Showing 1 changed file with 46 additions and 0 deletions.
46 changes: 46 additions & 0 deletions js/promises/promises.go
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
})
}
}

0 comments on commit 606d2ee

Please sign in to comment.