1 | {isPromise, isObject, isFunction, isGeneratorFunction} = require "./type"
|
2 |
|
3 | unhandled = new Map
|
4 |
|
5 |
|
6 | process.on "unhandledRejection", (reason, p) ->
|
7 | console.warn "Warning: unhandled rejection for", p
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 | promise = (executor) -> new Promise executor
|
22 |
|
23 | reject = (x) -> Promise.reject x
|
24 | resolve = (x) -> Promise.resolve x
|
25 |
|
26 |
|
27 |
|
28 | follow = resolve
|
29 |
|
30 | lift = (f) ->
|
31 | if isObject f
|
32 | proxy = {}
|
33 | for key, value of f when isFunction value
|
34 | proxy[key] = lift value
|
35 | proxy
|
36 | else
|
37 | (args...) ->
|
38 | promise (resolve, reject) ->
|
39 | try
|
40 | f args..., (error, _args...) ->
|
41 | unless error?
|
42 | resolve _args...
|
43 | else
|
44 | reject error
|
45 | catch error
|
46 | reject error
|
47 |
|
48 |
|
49 |
|
50 |
|
51 | async = (g) ->
|
52 |
|
53 | if !(isGeneratorFunction g)
|
54 | throw new TypeError "#{g} is not a generator function"
|
55 |
|
56 | (args...) ->
|
57 | self = this
|
58 | promise (resolve, reject) ->
|
59 | i = g.apply self, args
|
60 | f = -> i.next()
|
61 | do step = (f) ->
|
62 | try
|
63 | {done, value} = f()
|
64 | catch error
|
65 | reject error
|
66 |
|
67 | if done
|
68 | resolve value
|
69 | else
|
70 | follow value
|
71 | .then (value) -> step -> i.next value
|
72 | .catch (error) -> step -> i.throw error
|
73 |
|
74 | call = (f) -> do async f
|
75 |
|
76 | module.exports = {promise, resolve, follow, reject, lift, async, call}
|