-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpromise.go
91 lines (66 loc) · 1.78 KB
/
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
//go:build js && wasm
package js
import (
"syscall/js"
"github.com/dairaga/js/v2/builtin"
)
type Promise interface {
Wrapper
Then(func(Value) any) Promise
Catch(func(Value) any) Promise
Finally(func() any) Promise
Await() Value
}
type promise js.Value
var _ Promise = promise{}
// -----------------------------------------------------------------------------
func (p promise) JSValue() Value {
return Value(p)
}
// -----------------------------------------------------------------------------
func (p promise) call(method string, f func(Value) any) Promise {
result := Value(p).Call(method, OnceFuncOf(func(_ Value, args []Value) any {
return f(args[0])
}))
return promise(result)
}
// -----------------------------------------------------------------------------
func (p promise) Then(f func(Value) any) Promise {
return p.call("then", f)
}
// -----------------------------------------------------------------------------
func (p promise) Catch(f func(Value) any) Promise {
return p.call("catch", f)
}
// -----------------------------------------------------------------------------
func (p promise) Finally(f func() any) Promise {
result := Value(p).Call("finally", OnceFuncOf(func(Value, []Value) any {
return f()
}))
return promise(result)
}
// -----------------------------------------------------------------------------
func (p promise) Await() Value {
ch := make(chan Value)
defer func() {
close(ch)
}()
p.Then(func(v Value) any {
ch <- v
return nil
}).Catch(func(v Value) any {
ch <- v
return nil
})
return <-ch
}
// -----------------------------------------------------------------------------
func PromiseOf(x Value) Promise {
if !builtin.Promise.Is(x) {
panic(ValueError{
Method: "PromiseOf",
Type: x.Type(),
})
}
return promise(x)
}