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鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a promises package with a New helper function #3176

Merged
merged 7 commits into from
Jul 10, 2023
Merged
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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
oleiade marked this conversation as resolved.
Show resolved Hide resolved
// 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.MakeHandledPromise(vu)
// go func() {
// v, err := someAsyncFunc()
// if err != nil {
// reject(err)
// return
// }
//
// resolve(v)
// }()
// return promise
// }
func MakeHandledPromise(vu modules.VU) (promise *goja.Promise, resolve func(result interface{}), reject func(reason interface{})) {

Check failure on line 30 in js/promises/promises.go

View workflow job for this annotation

GitHub Actions / lint

line is 131 characters (lll)
oleiade marked this conversation as resolved.
Show resolved Hide resolved
runtime := vu.Runtime()
promise, resolve, reject = runtime.NewPromise()
callback := vu.RegisterCallback()

return promise, func(i interface{}) {
callback(func() error {
resolve(i)
return nil
})
}, func(i interface{}) {
callback(func() error {
reject(i)
return nil
})
}
}