OSDN Git Service

Regular updates
[twpd/master.git] / qjs.md
1 ---
2 title: Q.js
3 category: JavaScript libraries
4 layout: 2017/sheet
5 ---
6
7 ### About
8 {: .-intro}
9
10 * <https://github.com/kriskowal/q>
11 * <https://github.com/kriskowal/q/wiki/API-Reference>
12
13 ### Creating promises (Q.promise)
14
15     Q.promise (ok, fail) =>
16       asyncFunction ->
17         if error
18           fail new Error("Failure")
19         else
20           ok(data)
21
22 ### For arrays
23
24     promises = [saveDisk(), saveCloud()]
25
26     # When all succeeds, or *at least one* error
27     Q.all(promises).done ->
28       alert "Saved"
29
30     # Same, but get the values
31     Q.all(promises).spread (a, b) ->
32       alert "Result A:" + a
33       alert "Result B:" + b
34
35     # When all either succeeds or errors
36     Q.allSettled(promises).done -> ...
37
38
39 ### Creating promises from Node
40
41     # Works like .call() or .apply()
42
43     Q.nfcall(FS.readFile, 'foo.txt', 'utf-8')
44     .then -> ...
45
46     Q.nfapply(FS.readFile, ['foo.txt', 'utf-8'])
47     .then -> ...
48
49     Q.npost(FS, 'readFile', ['foo.txt, 'utf-8'])
50     .then -> ...
51
52     Q.npost(FS, 'readFile', 'foo.txt, 'utf-8')
53     .then -> ...
54
55     readFile = Q.denodeify(FS.readFile)
56     readFile('foo.txt').then -> ...
57
58 ### Promises to Node async
59
60     createUser = (next) ->
61       promiseMaker()
62       .nodeify(next)
63
64 ### Promise sugars
65
66     # Shortcut for .then(ok, fail, progress)
67     promise
68     .then (data) ->
69     .catch (err) ->
70     .progress (percent) ->
71
72 ### Try
73
74   Q.try ->
75     promise()
76
77   .catch (e) ->
78     console.error "Oh well", e