MCPcopy Create free account
hub / github.com/buke/quickjs-go / NewAsyncFunction

Method NewAsyncFunction

context.go:739–777  ·  view source on GitHub ↗

NewAsyncFunction returns a js async function value with given function template Deprecated: Use Context.NewFunction + Context.NewPromise instead for better memory management and thread safety. Example: asyncFn := ctx.NewFunction(func(ctx *quickjs.Context, this *quickjs.Value, args []*quickjs.Valu

(asyncFn func(ctx *Context, this *Value, promise *Value, args []*Value) *Value)

Source from the content-addressed store, hash-verified

737// })
738// })
739func (ctx *Context) NewAsyncFunction(asyncFn func(ctx *Context, this *Value, promise *Value, args []*Value) *Value) *Value {
740 // New implementation using Function + Promise
741 return ctx.NewFunction(func(ctx *Context, this *Value, args []*Value) *Value {
742 return ctx.NewPromise(func(resolve, reject func(*Value)) {
743 // Create a promise object that has resolve/reject methods
744 promiseObj := ctx.NewObject()
745 promiseObj.Set("resolve", ctx.NewFunction(func(ctx *Context, this *Value, args []*Value) *Value {
746 if len(args) > 0 {
747 resolve(args[0])
748 } else {
749 resolve(ctx.NewUndefined())
750 }
751 return ctx.NewUndefined()
752 }))
753 promiseObj.Set("reject", ctx.NewFunction(func(ctx *Context, this *Value, args []*Value) *Value {
754 if len(args) > 0 {
755 reject(args[0])
756 } else {
757 errObj := ctx.NewError(fmt.Errorf("Promise rejected without reason"))
758 defer errObj.Free() // Free the error object
759 reject(errObj)
760 }
761 return ctx.NewUndefined()
762 }))
763 defer promiseObj.Free()
764
765 // Call the original async function with the promise object
766 result := asyncFn(ctx, this, promiseObj, args)
767
768 // If the function returned a value directly (not using promise.resolve/reject),
769 // we resolve with that value
770 if !result.IsUndefined() {
771 resolve(result)
772 result.Free() // Free the result if it's not undefined
773 }
774
775 })
776 })
777}
778
779// AsyncFunction returns a js async function value with given function template
780//

Callers 2

TestContextAsyncFunctionFunction · 0.95
AsyncFunctionMethod · 0.95

Calls 8

NewFunctionMethod · 0.95
NewPromiseMethod · 0.95
NewObjectMethod · 0.95
NewUndefinedMethod · 0.95
NewErrorMethod · 0.95
SetMethod · 0.80
IsUndefinedMethod · 0.80
FreeMethod · 0.45

Tested by 1

TestContextAsyncFunctionFunction · 0.76