OSDN Git Service

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