forked from kriskowal/q
/
README
642 lines (459 loc) · 17.5 KB
/
README
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
Provides a defer/when style promise API for JavaScript
- usable as a CommonJS module, in Node,
- usable as a <script> in all web browsers,
- inspired by Tyler Close's Waterken ref_send promises, and
- compliant with
- http://wiki.commonjs.org/wiki/Promises/A
- http://wiki.commonjs.org/wiki/Promises/B
- http://wiki.commonjs.org/wiki/Promises/D
For Node:
$ curl http://npmjs.org/install.sh | sh
$ npm install q
$ node examples/test.js
EXAMPLES
--------
Promises from callbacks
function delay(ms) {
var deferred = Q.defer();
setTimeout(deferred.resolve, ms);
return deferred.promise;
}
Timeout
function timeout(promise, ms) {
var deferred = Q.defer();
Q.when(promise, deferred.resolve);
Q.when(delay(ms), function () {
deferred.reject("Timed out");
});
return deferred.promise;
}
Promises with rejection from Node callbacks
function wrap(wrapped) {
var deferred = Q.defer();
wrapped(function (error, result) {
if (error) {
deferred.reject(error);
} else {
deferred.resolve(result);
}
});
return deferred.promise;
}
When Blocks
var bPromise = Q.when(aPromise, function (aValue) {
return bValue;
});
var bPromise = Q.when(aPromise, function (aValue) {
return bValue;
}, function (aReason) {
throw bReason;
});
Parallel Join
var aPromise = aFunction();
var bPromise = bFunction();
var cPromise = Q.when(aPromise, function (aValue) {
return Q.when(bPromise, function bValue) {
return cValue;
});
});
Serial Join
var aPromise = aFunction();
var cPromise = Q.when(aPromise, function (aValue) {
// bFunction will not proceed unless aPromise
// is fulfilled
var bPromise = bFunction();
return Q.when(bPromise, function bValue) {
return cValue;
});
});
Recovering from Failure
function justDoIt(value) {
var work = doIt(value);
work = timeout(1000, work);
return Q.when(work, function (work) {
return work;
}, function errback(reason) {
// just do it again
return justDoIt(value);
});
}
Array Parallel Join
var done;
array.forEach(function (value) {
var work = doWork(value);
done = Q.when(done, function () {
return work;
});
});
return done;
Or
return array.reduce(function (done, value) {
var work = doWork(value);
return Q.when(done, function () {
return work;
});
}, undefined);
Array Serial Join
var done;
array.forEach(function (value) {
done = Q.when(done, function () {
return doWork(value);
});
});
return done;
Or
return array.reduce(function (done, value) {
return Q.when(done, function () {
return doWork(value);
});
});
Conditional Array Serial Join
var otherwise = function () {
throw new Error("No dice");
};
array.forEach(function (value) {
otherwise = (function (otherwise) {
return function () {
var work = doWork(value);
return Q.when(work, function (work) {
if (keepGoing(work)) {
return work;
} else {
return otherwise();
}
});
};
})(otherwise);
});
return otherwise();
Or
array.reduce(function (otherwise, value) {
var work = doWork(value);
return Q.when(work, function (work) {
if (keepGoing(work)) {
return work;
} else {
return otherwise();
}
});
}, function otherwise() {
throw new Error("No dice");
});
In Node, this example reads itself and writes itself out in
all capitals.
var Q = require("q/util");
var FS = require("q-fs");
var text = FS.read(__filename);
Q.when(text, function (text) {
console.log(text.toUpperCase());
});
You can also perform actions in parallel. This example
reads two files at the same time and returns an array of
promises for the results.
var Q = require("q/util");
var FS = require("q-fs");
var self = FS.read(__filename);
var passwd = FS.read("/etc/passwd");
Q.join(self, passwd, function (self, passwd) {
console.log(__filename + ':', self.length);
console.log('/etc/passwd:', passwd.length);
});
This example reads all of the files in the same directory as
the program and notes the length of each, in the order in
which they are finished reading.
var Q = require("q/util");
var FS = require("q-fs");
var list = FS.list(__dirname);
var files = Q.when(list, function (list) {
list.forEach(function (fileName) {
var content = FS.read(fileName);
Q.when(content, function (content) {
console.log(fileName, content.length);
});
});
});
This example reads all of the files in the same directory as
the program and notes the length of each, in the order in
which they were listed.
var list = FS.list(__dirname);
var files = Q.when(list, function (list) {
return list.reduce(function (ready, fileName) {
var content = FS.read(fileName);
return Q.join(ready, content, function (ready, content) {
console.log(fileName, content.length);
});
});
});
The Q Ecosystem
---------------
q-fs https://github.com/kriskowal/q-fs
basic file system promises
q-http https://github.com/kriskowal/q-http
http client and server promises
q-util https://github.com/kriskowal/q-util
promise control flow and data structures
q-comm https://github.com/kriskowal/q-comm
remote object communication
teleport https://github.com/gozala/teleport
browser-side module promises
...
All available through NPM.
THE HALLOWED API
----------------
when(value, callback_opt, errback_opt)
Arranges for a callback to be called:
- with the value as its sole argument
- in a future turn of the event loop
- if and when the value is or becomes a fully resolved
Arranges for errback to be called:
- with a value respresenting the reason why the object will
never be resolved, typically a string.
- in a future turn of the event loop
- if the value is a promise and
- if and when the promise is rejected
Returns a promise:
- that will resolve to the value returned by either the callback
or errback, if either of those functions are called, or
- that will be rejected if the value is rejected and no errback
is provided, thus forwarding rejections by default.
The value may be truly _any_ value.
The callback and errback may be falsy, in which case they will not
be called.
Guarantees:
- The callback will not be called before when returns.
- The errback will not be called before when returns.
- The callback will not be called more than once.
- The errback will not be called more than once.
- If the callback is called, the errback will never be called.
- If the errback is called, the callback will never be called.
- If a promise is never resolved, neither the callback or the
errback will ever be called.
THIS IS COOL
- You can set up an entire chain of causes and effects in the
duration of a single event and be guaranteed that any
invariants in your lexical scope will not...vary.
- You can both receive a promise from a sketchy API and return a
promise to some other sketchy API and, as long as you trust
this module, all of these guarantees are still provided.
- You can use when to compose promises in a variety of ways:
INTERSECTION
function and(a, b) {
return when(a, function (a) {
return when(b, function (b) {
// ...
});
})
}
defer()
Returns a "Deferred" object with a:
- promise property
- resolve(value) function
- reject(reason) function
The promise is suitable for passing as a value to
the "when" function.
Calling resolve with a promise notifies all observers
that they must now wait for that promise to resolve.
Calling resolve with a rejected promise notifies all
observers that the promise will never be fully resolved
with the rejection reason. This forwards through the
the chain of "when" calls and their returned "promises"
until it reaches a "when" call that has an "errback".
Calling resolve with a fully resolved value notifies
all observers that they may proceed with that value
in a future turn. This forwards through the "callback"
chain of any pending "when" calls.
Calling reject with a reason is equivalent to
resolving with a rejection.
In all cases where the resolution of a promise is set,
(promise, rejection, value) the resolution is permanent
and cannot be reset. All future observers of the
resolution of the promise will be notified of the
resolved value, so it is safe to call "when" on
a promise regardless of whether it has been or will
be resolved.
THIS IS COOL
The Deferred separates the promise part from the resolver
part. So:
- You can give the promise to any number of consumers
and all of them will observe the resolution independently.
Because the capability of observing a promise is separated
from the capability of resolving the promise, none of the
recipients of the promise have the ability to "trick"
other recipients with misinformation.
- You can give the resolver to any number of producers
and whoever resolves the promise first wins. Furthermore,
none of the producers can observe that they lost unless
you give them the promise part too.
UNION
function or(a, b) {
var union = defer();
when(a, union.resolve);
when(b, union.resolve);
return union.promise;
}
ref(value)
If value is a promise, returns the promise.
If value is not a promise, returns a promise that has
already been resolved with the given value.
def(value)
Annotates a value, wrapping it in a promise, such that
that it is a local promise object which cannot be
serialized and sent to resolve a remote promise.
A def'ed value will respond to the `isDef` message
without a rejection so remote promise communication
libraries can distinguish it from non-def values.
reject(reason)
Returns a promise that has already been rejected
with the given reason.
This is useful for conditionally forwarding a rejection
through an errback.
when(API.getPromise(), function (value) {
return doSomething(value);
}, function (reason) {
if (API.stillPossible())
return API.tryAgain();
else
return reject(reason);
})
Unconditionally forwarding a rejection is equivalent to
omitting an errback on a when call.
isPromise(value)
Returns whether the given value is a promise.
isResolved(value)
Returns whether the given value is fully resolved.
The given value may be any value, including
but not limited to promises returned by defer() and
ref(). Rejected promises are not considered
resolved.
isRejected(value)
Returns whether the given value is a rejected
promise.
promise.valueOf()
Promises override their valueOf method such that if the
promise is fully resolved, it will return the fully
resolved value.
error(reason)
Accepts a reason and throws an error. This is a
convenience for when calls where you want to trap the
error clause and throw it instead of attempting a
recovery or forwarding.
enqueue(callback Function)
Calls "callback" in a future turn.
ADVANCED API
------------
The "ref" promise constructor establishes the basic API for
performing operations on objects: "get", "put", "post", and
"del". This set of "operators" can be extended by creating
promises that respond to messages with other operator names,
and by sending corresponding messages to those promises.
makePromise(descriptor, fallback_opt, valueOf_opt)
Creates a stand-alone promise that responds to messages.
These messages have an operator like "when", "get",
"put", and "post", corresponding to each of the above
methods for sending messages to promises.
The descriptor is an object with function properties
(methods) corresponding to operators. When the made
promise receives a message and a corresponding operator
exists in the descriptor, the method gets called with
the variadic arguments sent to the promise. If no
descriptor exists, the fallback method is called with
the operator, and the subsequent variadic arguments
instead. These functions return a promise for the
eventual resolution of the promise returned by the
message-sender. The default fallback returns a
rejection.
The `valueOf` function, if provided, overrides the
`valueOf` method of the returned promise. This is
useful for providing information about the promise in
the same turn of the event loop. For example, resolved
promises return their resolution value and rejections
return an object that is recognized by `isRejected`.
send(value, operator, ...args)
Sends an arbitrary message to a promise.
Care should be taken not to introduce control-flow
hazards and secuirity holes when forwarding messages to
promises. The methods above, particularly "when", are
carefully crafted to prevent a poorly crafted or
malicious promise from breaking the invariants like not
applying callbacks multiple times or in the same turn of
the event loop.
THE UTIL MODULE
---------------
The Q utility module exports all of the Q module's API but
additionally provides the following functions.
var Q = require("q/util");
step(...functions)
Calls each step function serially, proceeding only when
the promise returned by the previous step is deeply
resolved (see: `deep`), and passes the resolution of the
previous step into the argument or arguments of the
subsequent step.
If a step accepts more than one argument, the resolution
of the previous step is treated as an array and expanded
into the step's respective arguments.
`step` returns a promise for the value eventually
returned by the last step.
delay(timeout, eventually_opt)
Returns a promise for the eventual value after `timeout`
miliseconds have elapsed. `eventually` may be omitted,
in which case the promise will be resolved to
`undefined`. If `eventually` is a function, progress
will be made by calling that function and resolving to
the returned value. Otherwise, `eventually` is treated
as a literal value and resolves the returned promise
directly.
shallow(object)
Takes any value and returns a promise for the
corresponding value after all of its properties have
been resolved. For arrays, this means that the
resolution is a new array with the corresponding values
for each respective promise of the original array, and
for objects, a new object with the corresponding values
for each property.
deep(object)
Takes any value and returns a promise for the
corresponding value after all of its properties have
been deeply resolved. Any array or object in the
transitive properties of the given value will be
replaced with a new array or object where all of the
owned properties have been replaced with their
resolution.
reduceLeft(values, callback, basis, this)
reduceRight(values, callback, basis, this)
reduce(values, callback, basis, this)
The reduce methods all have the signature of `reduce` on
an ECMAScript 5 `Array`, but handle the cases where a
value is a promise and when the return value of the
accumulator is a promise. In these cases, each reducer
guarantees that progress will be made in a particular
order.
`reduceLeft` guarantees that the callback will be called
on each value and accumulation from left to right after
all previous values and accumulations are fully
resolved.
`reduceRight` works similarly from right to left.
`reduce` is opportunistic and will attempt to accumulate
the resolution of any previous resolutions. This is
useful when the accumulation function is associative.
THE QUEUE MODULE
----------------
The `q/queue` module provides a `Queue` object where
infinite promises for values can be dequeued before they are
enqueued.
put(value)
Places a value on the queue, resolving the next gotten
promise in order.
get()
Returns a promise for the next value from the queue. If
more values have been enqueued than dequeued, this value
will already be resolved.
close(reason_opt)
Causes all promises dequeued after all already enqueued
values have been depleted will be rejected for the given
reason.
closed
A promise that, when resolved, indicates that all
enqueued values from before the call to `close` have
been dequeued.
Copyright 2009, 2010 Kristopher Michael Kowal
MIT License (enclosed)