Skip to content

Commit

Permalink
Merge ebd3486 into c995529
Browse files Browse the repository at this point in the history
  • Loading branch information
oleiade committed Jul 10, 2023
2 parents c995529 + ebd3486 commit e9f12c3
Showing 1 changed file with 45 additions and 0 deletions.
45 changes: 45 additions & 0 deletions js/promises/promises.go
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
})
}
}

0 comments on commit e9f12c3

Please sign in to comment.