UNPKG

1.85 kBtext/coffeescriptView Raw
1{isPromise, isObject, isFunction, isGeneratorFunction} = require "./type"
2
3unhandled = new Map
4
5# TODO: make this configurable?
6process.on "unhandledRejection", (reason, p) ->
7 console.warn "Warning: unhandled rejection for", p
8
9# Example, adapted from Node docs, that defers reporting
10#
11# process.on "unhandledRejection", (reason, p) ->
12# unhandled.set p, reason
13#
14# process.on "rejectionHandled", (p) ->
15# unhandled.delete p
16#
17# process.on "exit", ->
18# unhandled.forEach (reason, p) ->
19# console.warn "Warning: unhandled rejection for", p
20
21promise = (executor) -> new Promise executor
22
23reject = (x) -> Promise.reject x
24resolve = (x) -> Promise.resolve x
25
26# follow reads better in some cases and avoids naming
27# conflicts within promise executors
28follow = resolve
29
30lift = (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# This code is adapted from:
49# http://tc39.github.io/ecmascript-asyncawait/#intro
50
51async = (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
74call = (f) -> do async f
75
76module.exports = {promise, resolve, follow, reject, lift, async, call}