♻️ Promise: More idiomatic Go...

This commit is contained in:
Nicolas Lepage 2021-01-27 23:21:59 +01:00
parent 896b5a3cee
commit b3e8d72ed1
No known key found for this signature in database
GPG Key ID: B0879E35E66D8F6F
5 changed files with 34 additions and 35 deletions

Binary file not shown.

Binary file not shown.

View File

@ -4,31 +4,30 @@ import (
"syscall/js"
)
// Promise is a JavaScript Promise
type Promise struct {
js.Value
}
// NewPromise creates a new JavaScript Promise
func NewPromise(cb func(resolve func(interface{}), reject func(interface{}))) Promise {
func NewPromise() (p js.Value, resolve func(interface{}), reject func(interface{})) {
var cbFunc js.Func
cbFunc = js.FuncOf(func(_ js.Value, args []js.Value) interface{} {
defer cbFunc.Release()
cb(
func(value interface{}) {
cbFunc.Release()
resolve = func(value interface{}) {
args[0].Invoke(value)
},
func(value interface{}) {
}
reject = func(value interface{}) {
args[1].Invoke(value)
},
)
}
return js.Undefined()
})
return Promise{js.Global().Get("Promise").New(cbFunc)}
p = js.Global().Get("Promise").New(cbFunc)
return
}
// Await waits for the Promise to be resolved and returns the value
func (p Promise) Await() (js.Value, error) {
func Await(p js.Value) (js.Value, error) {
resCh := make(chan js.Value)
var then js.Func
then = js.FuncOf(func(_ js.Value, args []js.Value) interface{} {

View File

@ -9,7 +9,7 @@ import (
// Request builds and returns the equivalent http.Request
func Request(r js.Value) *http.Request {
jsBody := js.Global().Get("Uint8Array").New(Promise{r.Call("arrayBuffer")}.Await())
jsBody := js.Global().Get("Uint8Array").New(Await(r.Call("arrayBuffer")))
body := make([]byte, jsBody.Get("length").Int())
js.CopyBytesToGo(body, jsBody)

View File

@ -26,7 +26,8 @@ func Serve(handler http.Handler) func() {
}
var cb = js.FuncOf(func(_ js.Value, args []js.Value) interface{} {
var resPromise = NewPromise(func(resolve func(interface{}), reject func(interface{})) {
var resPromise, resolve, reject = NewPromise()
go func() {
defer func() {
if r := recover(); r != nil {
@ -44,7 +45,6 @@ func Serve(handler http.Handler) func() {
resolve(res)
}()
})
return resPromise
})