forked from kriskowal/q
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathREADME2
87 lines (67 loc) · 2.65 KB
/
README2
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
Thenables
---------
The Q API supports CommonJS/Promises/A, Kris Zyp's proposal
for "thenable" promises. A thenable is any object with a
"then(callback, errback)" method. The "then" method, in
turn, returns a promise for whatever value the callback's
eventually return. Thus, promises are chainable.
Let's review Tim's example. This illustrates the same
concept as the first example. We asynchronously read our
own program and print it out in all capitals.
var Q = require("q");
var FS = require("q-fs");
Q.when(FS.read(__filename))
.then(function (text) {
return text.toUpperCase();
}).then(function (text) {
console.log(text);
});
/!\ IMPORTANT
The call to "Q.when" is not necessary but provides many
assurances that, even if the FS API is poorly written or
even if it is *maliciously* written, that the promise
returned will behave consistently. That means that your
callbacks will all occur in future turns of the event loop
(so the state in your closure doesn't change), and that one
callback for each "thenable" will ever be called (so that
the state in your closure doesn't change more than once).
This example uses the "q/util" module again, because it has
that lovely "deep" method for turning objects with promises
inside-out (to a promise for an object).
var Q = require("q/util");
var FS = require("q-fs");
Q.when(Q.deep({
"self": FS.read(__filename),
"passwd": FS.read("/etc/passwd")
})).then(function (texts) {
console.log(__filename + ":" + texts.self.length);
console.log("/ext/passwd:" + texts.passwd.length);
});
In this case, we've simultaneously read the text of our own
program, and the Unix user database, and then printed out
their corresponding file sizes.
Finally, to read all of the files in the examples directory
and note the lengths of each one, we can use a three step
thenable:
var Q = require("q/util");
var FS = require("q-fs");
Q.when(FS.list(__dirname))
.then(function (fileNames) {
return Q.deep(fileNames.map(function (fileName) {
return {
"name": fileName,
"text": FS.read(FS.join(__dirname, fileName))
};
}));
}).then(function (files) {
files.forEach(function (file) {
console.log(file.name, file.text.length);
});
});
Again, all of these examples are in the `examples` directory
with the names `then{1,2,3}.js`.
Quacks Like a Duck:
Any object with a "then(callback, errback)" method will be
treated as a promise, and all promises provided by the Q API
have "then" methods so they can be used by any API that
accepts thenables.