forked from RoganDawes/P4wnP1_aloa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
promise.go
52 lines (39 loc) · 902 Bytes
/
promise.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package main
import (
"github.com/gopherjs/gopherjs/js"
)
type Promise struct {
*js.Object
State string `js:"state"` //ToDo: change to dedicated type
}
type PromiseFunc func() (result interface{}, err error)
func NewPromise(pf PromiseFunc) (p *Promise) {
f := func(resolve *js.Object, reject *js.Object) {
p := &struct {
*js.Object
Resolve *js.Object `js:"resolve"`
Reject *js.Object `js:"reject"`
}{Object:O()}
p.Resolve = resolve
p.Reject = reject
fResolve := func(args interface{}) (res interface{}) {
return p.Call("resolve",args)
}
fReject := func(args interface{}) (res interface{}) {
return p.Call("reject",args)
}
go func() {
res,err := pf()
if err != nil {
fReject(js.Global.Get("Error").New(err.Error()))
} else {
fResolve(res)
}
}()
}
jsP := js.Global.Get("Promise").New(f)
p = &Promise{
Object: jsP,
}
return
}