Debian Codegraph @

deferred/README.md

raw
1 [![Build status][semaphore-image]][semaphore-url]
2 [![Windows status][appveyor-image]][appveyor-url]
3 [![Transpilation status][transpilation-image]
4 [![npm version][npm-image]][npm-url]
5
6 # Deferred
7
8 ## Modular and fast Promises implementation for JavaScript
9
10 _Implementation originally inspired by Kris Kowal's [Q](https://github.com/kriskowal/q)_
11
12 Deferred is complete, [one of the fastest](#performance) and natural promise implementation in JavaScript, with Deferred you can write [clear maintainable code](#promises-approach) that takes maximum out of asynchronicity, in fact due to multi-dimensional nature of promises ([chaining](#chaining) and [nesting](#nesting)) you're forced to program declaratively.
13
14 With Deferred you also can: [Process collections](#processing-collections) of deferred calls. [Handle Node.js asynchronous functions](#working-with-asynchronous-functions). [Limit concurrency](#limiting-concurrency) of scheduled tasks. [Emit progress events](#progress-and-other-events) or [stream results partially](#streaming-data-partially) on the go.
15
16 In the end you may debug your flow by [tracking unresolved promises](#monitoring-unresolved-promises) or gathering [usage statistics](#usage-statistics).
17
18 _For good insight into promise/deferred concept and in general asynchronous programming see also slides from meetjs summit presentation: [Asynchronous JavaScript](http://www.medikoo.com/asynchronous-javascript/)_
19
20 **If you need help with deferred, please ask on dedicated mailing list: [[email protected]](https://groups.google.com/forum/#!forum/deferred-js)**
21
22 ### Comparision with callback style
23
24 Example of JavaScript files concatenation:
25
26 #### Plain Node.js, callbacks approach
27
28 ```javascript
29 var fs = require("fs");
30
31 var readdir = fs.readdir;
32 var readFile = fs.readFile;
33 var writeFile = fs.writeFile;
34
35 // Read all filenames in given path
36 readdir(__dirname, function (err, files) {
37 var result, waiting;
38 if (err) {
39 // if we're unable to get file listing throw error
40 throw err;
41 }
42
43 // Filter *.js files and generated lib.js
44 files = files.filter(function (file) { return file.slice(-3) === ".js" && file !== "lib.js"; });
45
46 // Read content of each file
47 waiting = 0;
48 result = [];
49 files.forEach(function (file, index) {
50 ++waiting;
51 readFile(file, function (err, content) {
52 if (err) {
53 // We were not able to read file content, throw error
54 throw err;
55 }
56 result[index] = content;
57
58 if (!--waiting) {
59 // Got content of all files
60 // Concatenate into one string and write into lib.js
61 writeFile(__dirname + "/lib.js", result.join("\n"), function (err) {
62 if (err) {
63 // We cannot write lib.js file, throw error
64 throw err;
65 }
66 });
67 }
68 });
69 });
70 });
71 ```
72
73 #### Implementation with promises:
74
75 ```javascript
76 var promisify = require("deferred").promisify;
77 var fs = require("fs");
78
79 // Convert node.js async functions, into ones that return a promise
80 var readdir = promisify(fs.readdir);
81 var readFile = promisify(fs.readFile, 1); // Restrict arity to 1 + callback
82 var writeFile = promisify(fs.writeFile);
83
84 writeFile(
85 __dirname + "/lib.js",
86 // Read all filenames in given path
87 readdir(__dirname)
88 // Filter *.js files and generated lib.js
89 .invoke("filter", function (file) { return file.slice(-3) === ".js" && file !== "lib.js"; })
90
91 // Read content of all files
92 .map(readFile)
93
94 // Concatenate files content into one string
95 .invoke("join", "\n")
96 ).done(); // If there was any error on the way throw it
97 ```
98
99 ### Examples
100
101 See [examples folder](examples) for a demonstration of promises usage in some other real world cases.
102
103 ### Installation
104
105 #### NPM
106
107 In your project path:
108
109 \$ npm install deferred
110
111 #### Browser
112
113 Browser bundle can be easily created with help of [modules-webmake](https://github.com/medikoo/modules-webmake). Assuming that you have latest [Node.js](http://nodejs.org/) and [Git](http://git-scm.com/) installed, following will work in command shell of any system (Linux/MacOS/Windows):
114
115 ```
116 $ npm install -g webmake
117 $ git clone git://github.com/medikoo/deferred.git
118 $ cd deferred
119 $ npm install
120 $ cd ..
121 $ webmake --name=deferred deferred/index.js deferred.js
122 ```
123
124 Last command bundles deferred with all it's functionalities, but you may need just a subset, you can have that by addressing specific modules directly, e.g. with following you will build just core functionality with map extension:
125
126 ```
127 $ webmake --name=deferred --include=deferred/ext/promise/map.js deferred/deferred.js deferred.js
128 ```
129
130 If you work with AMD modules, use _amd_ option, so generated bundle is one:
131
132 ```
133 $ webmake --amd deferred/index.js deferred.js
134 ```
135
136 _Mind that deferred relies on some ECMAScript5 features, so for older browsers you need to load as well [es5-shim](https://github.com/kriskowal/es5-shim)_
137
138 ### Deferred/Promise concept
139
140 #### Deferred
141
142 For work that doesn't return immediately (asynchronous) you may create deferred object. Deferred holds both `resolve` and `promise` objects. Observers interested in value are attached to `promise` object, with `resolve` we resolve promise with an actual value. In common usage `promise` is returned to the world and `resolve` is kept internally
143
144 Let's create `delay` function decorator:
145
146 ```javascript
147 var deferred = require('deferred');
148
149 var delay = function (fn, timeout) {
150 return function () {
151 var def = deferred(), self = this, args = arguments;
152
153 setTimeout(function () {
154 var value;
155 try {
156 value = fn.apply(self, args));
157 } catch (e) {
158 def.reject(e);
159 return;
160 }
161 def.resolve(value);
162 }, timeout);
163
164 return def.promise;
165 };
166 };
167
168 var delayedAdd = delay(function (a, b) {
169 return a + b;
170 }, 100);
171
172 var resultPromise = delayedAdd(2, 3);
173
174 console.log(deferred.isPromise(resultPromise)); // true
175
176 resultPromise(function (value) {
177 // Invoked after 100 milliseconds
178 console.log(value); // 5
179 });
180 ```
181
182 #### Promise
183
184 Promise is an object that represents eventual value which may already be available or is expected to be available in a future. Promise may succeed (fulfillment) or fail (rejection). Promise can be resolved only once.
185 In `deferred` (and most of the other promise implementations) you may listen for the value by passing observers to `then` function:
186
187 ```javascript
188 promise.then(onsuccess, onfail);
189 ```
190
191 In **deferred** promise is really a `then` function, so you may use promise _function_ directly:
192
193 ```javascript
194 promise === promise.then; // true
195 promise(onsuccess, onfail);
196 ```
197
198 **If you want to keep clear visible distinction between promises and other object I encourage you to always use `promise.then` notation.**
199
200 Both callbacks `onsuccess` and `onfail` are optional. They will be called only once and only either `onsuccess` or `onfail` will be called.
201
202 ##### Chaining
203
204 Promises by nature can be chained. `promise` function returns another promise which is resolved with a value returned by a callback function:
205
206 ```javascript
207 delayedAdd(2, 3)(function (result) { return result * result; })(function (result) {
208 console.log(result); // 25
209 });
210 ```
211
212 It's not just functions that promise function can take, it can be other promises or any other JavaScript value (with exception of `null` or `undefined` which will be treated as no value). Going that way you may override result of a promise chain with specific value.
213
214 ##### Nesting
215
216 Promises can be nested. If a promise resolves with another promise, it's not really resolved. It's resolved only when final promise is resolved with a real value:
217
218 ```javascript
219 var def = deferred();
220 def.resolve(delayedAdd(2, 3)); // Resolve promise with another promise
221 def.promise(function (result) {
222 console.log(result); // 5;
223 });
224 ```
225
226 ##### Error handling
227
228 Errors in promises are handled with separate control flow, that's one of the reasons why code written with promises is more readable and maintainable than when using callbacks approach.
229
230 A promise resolved with an error (rejected), propagates its error to all promises that depend on this promise (e.g. promises initiated by adding observers).
231 If observer function crashes with error or returns error, its promise is rejected with the error.
232
233 To handle error, pass dedicated callback as second argument to promise function:
234
235 ```javascript
236 delayedAdd(2, 3)(function (result) { throw new Error("Error!"); })(
237 function () {
238 // never called
239 },
240 function (e) {
241 // handle error;
242 }
243 );
244 ```
245
246 ##### Ending chain
247
248 To expose the errors that are not handled, end promise chain with `.done()`, then error that broke the chain will be thrown:
249
250 ```javascript
251 delayedAdd(2, 3)(function (result) { throw new Error("Error!"); })(function (result) {
252 // never executed
253 }).done(); // throws error!
254 ```
255
256 **It's important to end your promise chains with `done` otherwise eventual ignored errors will not be exposed**.
257
258 Signature of `done` function is same as for `then` (or promise itself)
259
260 `done` is aliased with `end` function, however `end` will be removed with introduction of v0.7 release.
261
262 ```javascript
263 promise(function (value) {
264 // process
265 }).done(
266 function (result) {
267 // process result
268 },
269 function (err) {
270 // handle error
271 }
272 );
273 ```
274
275 And as with `then` either callback can be provided. If callback for error was omitted, eventual error will be thrown.
276
277 ##### Creating resolved promises
278
279 You may create initially resolved promises.
280
281 ```javascript
282 var promise = deferred(1);
283
284 promise(function (result) {
285 console.log(result); // 1;
286 });
287 ```
288
289 ### Working with asynchronous functions
290
291 #### promisify(fn[, length])
292
293 There is a known convention (coined by Node.js) for working with asynchronous calls. An asynchronous function receives a callback argument which handles both eventual error and expected value:
294
295 ```javascript
296 var fs = require("fs");
297
298 fs.readFile(__filename, "utf-8", function (err, content) {
299 if (err) {
300 // handle error;
301 return;
302 }
303 // process content
304 });
305 ```
306
307 It's not convenient to work with both promises and callback style functions. When you decide to build your flow with promises **don't mix both concepts, just `promisify` asynchronous functions so they return promises instead**.
308
309 ```javascript
310 var deferred = require("deferred")
311 , fs = require("fs")
312 , readFile = deferred.promisify(fs.readFile);
313
314 readFile(__filename, "utf-8")(
315 function (content) {
316 // process content
317 },
318 function (err) {
319 // handle error
320 }
321 );
322 ```
323
324 `promisify` accepts also second argument, through which we may specify length of arguments that function takes (not counting callback argument), it may be handy if there's a chance that unexpected arguments will be passed to function (e.g. Array's `forEach` or `map`)
325
326 `promisify` also takes care of input arguments. **It makes sure that all arguments that are to be passed to asynchronous function are first resolved.**
327
328 #### callAsync(fn, context, ...args)
329
330 If for some reason you need to turn asynchronous functions into ones that return promises, inline in algorithm, then `callAsync` is for you.
331
332 Still mind that `promisify` is much better (cleaner) choice if it's possible to prepare reusable wrapper upfront.
333
334 ```javascript
335 var callAsync = require("deferred").callAsync;
336
337 callAsync(someAsyncFn, context, arg1, arg2).done(function (result) {
338 // process result
339 });
340 ```
341
342 #### invokeAsync(obj, fnName | fn, ...args)
343
344 If you need to turn asynchronous methods to ones that return promises, and you prefer not to augment its class prototypes, `invokeAsync` addresses that use case.
345
346 ```javascript
347 var invokeAsync = require("deferred").invokeAsync;
348
349 invokeAsync(db, "find", "books", { title: "Some title" }).done(function (book) {
350 // process result
351 });
352 ```
353
354 ## Grouping promises
355
356 When we're interested in results of more than one promise object we may group them into one promise with `deferred` function:
357
358 ```javascript
359 deferred(delayedAdd(2, 3), delayedAdd(3, 5), delayedAdd(1, 7))(function (result) {
360 console.log(result); // [5, 8, 8]
361 });
362 ```
363
364 ### Processing collections
365
366 #### Map
367
368 It's analogous to Array's map, with that difference that it returns promise (of an array) that would be resolved when promises for all items are resolved. Any error that would occur will reject the promise and resolve it with same error.
369
370 In following example we take content of each file found in an array:
371
372 ```javascript
373 var readFile = deferred.promisify(fs.readFile);
374
375 deferred.map(filenames, function (filename) { return readFile(filename, "utf-8"); })(function (
376 result
377 ) {
378 // result is an array of file's contents
379 });
380 ```
381
382 `map` is also available directly on a promise object, so we may invoke it directly on promise of a collection.
383
384 Let's try again previous example but this time instead of relying on already existing filenames, we take list of files from current directory:
385
386 ```javascript
387 var readdir = deferred.promisify(fs.readdir);
388 var readFile = deferred.promisify(fs.readFile);
389
390 readdir(__dirname).map(function (filename) { return readFile(filename, "utf-8"); })(function (
391 result
392 ) {
393 // result is an array of file's contents
394 });
395 ```
396
397 This function is available also as an extension on promise object.
398
399 **See [limiting concurrency](#limiting-concurrency) section for info on how to limit maximum number of concurrent calls in `map`**
400
401 #### Reduce
402
403 It's same as Array's reduce with that difference that it calls callback only after previous accumulated value is resolved, this way we may accumulate results of collection of promises or invoke some asynchronous tasks one after another.
404
405 ```javascript
406 deferred.reduce([delayedAdd(2, 3), delayedAdd(3, 5), delayedAdd(1, 7)], function (a, b) {
407 return delayedAdd(a, b);
408 })(function (result) {
409 console.log(result); // 21
410 });
411 ```
412
413 This function is available also as an extension on promise object.
414
415 #### Some
416
417 Promise aware Array's some. Process collection one after another and stop when first item matches your criteria
418
419 ```javascript
420 deferred.some([filename1, filename2, filename3], function (filename) {
421 return readFile(filename, "utf8", function (data) {
422 if (data.indexOf("needle")) {
423 // Got it! Stop further processing
424 return true;
425 }
426 });
427 });
428 ```
429
430 This function is available also as an extension on promise object.
431
432 ### Limiting concurrency
433
434 There are cases when we don't want to run too many tasks simultaneously. Like common case in Node.js when we don't want to open too many file descriptors.
435
436 Handle that with `deferred.gate`, it wraps functions that return promises. It doesn't do anything to promise objects, it just limits creation of them by blocking calls to function it wraps.
437
438 ```javascript
439 var fn = deferred.gate(function async() {
440 var def = deferred();
441 // ..
442 return def.promise;
443 }, 10);
444 ```
445
446 If there are already 10 concurrent tasks running `async` function invocation will be postponed into the queue and released when first of the running tasks will finish its job.
447
448 Additionally with third argument, we may limit number of postponed calls, so if there's more than _n_ of them rest is discarded. In below example, queue holds maximum 3 postponed calls, rest will be discarded.
449
450 ```javascript
451 var fn = deferred.gate(function async() { .. }, 10, 3);
452 ```
453
454 In following example we'll limit concurrent readFile calls when using deferred.map:
455
456 ```javascript
457 // Open maximum 100 file descriptors at once
458 deferred.map(
459 filenames,
460 deferred.gate(function (filename) { return readFile(filename, "utf-8"); }, 100)
461 )(function (result) {
462 // result is an array of file's contents
463 });
464 ```
465
466 ### Progress and other events
467
468 **Promise objects are also an event emitters**. Deferred implementation is backed by cross-environment [event-emitter solution](https://github.com/medikoo/event-emitter)
469
470 Simple Ajax file uploader example:
471
472 ```javascript
473 var ajaxFileUploader = function (url, data) {
474 var def = deferred();
475 var xhr = new XMLHttpRequest();
476
477 xhr.open("POST", url, true);
478 xhr.onload = def.resolve;
479 xhr.onerror = function () { def.resolve(new Error("Could not upload files")); };
480 xhr.upload.onprogress = function (e) { def.promise.emit("progress", e); };
481 xhr.send(data);
482 return def.promise;
483 };
484
485 var upload = ajaxFileUploader(formData);
486 upload.on("progress", function () {
487 // process progress events
488 });
489 upload.done(function (e) {
490 // All files uploaded!
491 });
492 ```
493
494 #### Streaming data partially
495
496 Another use case would be to provide obtained data partially on the go (stream like).
497 Imagine recursive directory reader that scans whole file system and provides filenames as it approaches them:
498
499 ```javascript
500 var reader = readdirDeep(rootPath); // reader promise is returned
501 reader.on("data", function (someFilenames) {
502 // Called many times during scan with obtained names
503 });
504 reader.done(function (allFilenames) {
505 // File-system scan finished!
506 });
507 ```
508
509 ### Promise extensions
510
511 Promise objects are equipped with some useful extensions. All extension are optional but are loaded by default when `deferred` is loaded via `require('deferred')` import.
512 When preparing client-side file (with help of e.g. [modules-webmake](https://github.com/medikoo/modules-webmake)) you are free to decide, which extensions you want to take (see source of `lib/index.js` on how to do that)
513
514 #### aside
515
516 Third brother of `then` and `done`. Has same signature but neither extends chain nor ends it, instead splits it by returning promise on which it was invoked. Useful when we want to return promise, but on a side (in parallel) do something else with obtained value:
517
518 ```javascript
519 var x = deferred({ foo: "bar" });
520 var promise = deferred({ foo: "bar" });
521
522 var y = promise.aside(function (value) {
523 console.log(value === x); // true
524 });
525 console.log(y === promise); // true
526 ```
527
528 #### catch
529
530 Same as `then` but accepts only `onFail` callback.
531
532 ```javascript
533 var def = deferred(), promise2;
534
535 promise2 = def.promise.catch(function () { return "Never mind"; });
536
537 def.reject(new Error("Error"));
538
539 promise2.done(function (value) {
540 console.log(value); // Prints "Never mind"
541 });
542 ```
543
544 #### cb
545
546 Convert back to callback style. Useful if you want to process regular callback at the end of promise chain. Simple use case would be regular asynchronous function built internally with promises. `cb` also makes sure that your callback is not called immediately but in next tick earliest.
547
548 With cb we may build hybrid functions that do both, handle asynchronous callback and return promise:
549
550 ```javascript
551 var asyncFunction = function (x, y, callback) {
552 return someAsyncProcessingThatReturnsPromise(x, y).cb(callback);
553 });
554 ```
555
556 #### finally
557
558 Invokes given callback when promise is either fulfilled or rejected
559
560 ```javascript
561 var prepare = function () { ... }
562 , cleanup = function () { ... }
563
564 prepare();
565 promise = asyncFn();
566 promise.finally(cleanup);
567 ```
568
569 #### get
570
571 To directly get to object property use `get`
572
573 ```javascript
574 var promise = deferred({ foo: "bar" });
575
576 promise(function (obj) {
577 console.log(obj.foo); // 'bar';
578 });
579
580 promise.get("foo")(function (value) {
581 console.log(value); // 'bar'
582 });
583 ```
584
585 You can get to nested properties as well:
586
587 ```javascript
588 var promise = deferred({ foo: { bar: 317 });
589
590 promise(function (obj) {
591 console.log(obj.foo.bar); // 317;
592 })
593
594 promise.get('foo', 'bar')(function (value) {
595 console.log(value); // 317
596 });
597 ```
598
599 #### invoke & invokeAsync
600
601 Schedule function call on returned object
602
603 ```javascript
604 var promise = deferred({ foo: function (arg) { return arg * arg; } });
605
606 promise.invoke("foo", 3)(function (result) {
607 console.log(result); // 9
608 });
609
610 // For asynchronous functions use invokeAsync
611 var promise = deferred({
612 foo: function (arg, callback) {
613 setTimeout(function () { callback(null, arg * arg); }, 100);
614 }
615 });
616
617 promise.invokeAsync("foo", 3)(function (result) {
618 console.log(result); // 9
619 });
620 ```
621
622 #### map
623
624 See [promise aware version of Array's map](#map).
625
626 #### reduce
627
628 See [promise aware version of Array's reduce](#reduce)
629
630 #### some
631
632 See [promise aware version of Array's some](#some)
633
634 #### spread
635
636 If promise expected value is a list that you want to spread into function arguments then use `spread`
637
638 ```javascript
639 var promise = deferred([2, 3]);
640
641 promise.spread(function (a, b) {
642 console.log(a + b); // 5
643 });
644 ```
645
646 #### timeout
647
648 Resolve with rejection ("Operation timeout" error with `DEFERRED_TIMEOUT` code), if given promise
649 won't settle with resolved value within given _timeout_
650
651 ```javascript
652 var deferred = new Deferred();
653
654 deferred.promise.timeout(30).done(function (value) {
655 console.log("Never called");
656 }, function () {
657 console.log("Rejected after 30 seconds");
658 });
659
660 deferred = new Deferred();
661 deferred.promise.timeout(30).done(function (value) {
662 console.log("Resolved with", value); // Resolved with true
663 }, function () {}
664 console.log("Never called");
665 });
666 setTimeout(function () {
667 deferred.resolve(true);
668 }, 10);
669 ```
670
671 ### Debugging
672
673 #### Monitoring unresolved promises
674
675 In properly constructed flow, there should be no promises that are never resolved.
676 If you want to be sure that it's not the case, or you suspect there are such issues, check whether deferred's monitor has something to say
677
678 ```javascript
679 deferred.monitor();
680 ```
681
682 By default monitor will log error for every promise that was not resolved in 5 seconds.
683 You can customize that timeout, and handle errors with your own listener:
684
685 ```javascript
686 deferred.monitor(10000, function (err) {
687 // Called for each promise not resolved in 10 seconds time
688 });
689 ```
690
691 This extension affects performance and it's best not to use it in production environment
692
693 #### Usage statistics
694
695 Being able to see how many promises were initialized (and where) in our flow can be helpful to track application issues, it's also good way to confirm that constructed flow works as intended.
696
697 ```javascript
698 deferred.profile(); // Start collecting statistics
699
700 //...
701
702 var stats = deferred.profileEnd(); // End profiling
703 console.log(stats.log); // See readable output
704 ```
705
706 Example log output:
707
708 ```
709 ------------------------------------------------------------
710 Deferred/Promise usage statistics:
711
712 104540 Total promises initialized
713 104540 Initialized as Unresolved
714 0 Initialized as Resolved
715
716 Unresolved promises were initialized at:
717 22590 at Object.module.exports.factory (/Users/medikoo/Projects/_packages/next/lib/fs/_memoize-watcher.js:21:10)
718 11553 at Object.IsIgnored.init (/Users/medikoo/Projects/_packages/next/lib/fs/is-ignored.js:140:18)
719 11553 at module.exports.factory (/Users/medikoo/Projects/_packages/next/lib/fs/_memoize-watcher.js:21:10)
720 7854 at Object.Readdir.filterIgnored (/Users/medikoo/Projects/_packages/next/lib/fs/readdir.js:434:23)
721 4619 at Object.module.exports.factory (/Users/medikoo/Projects/_packages/next/lib/fs/_memoize-watcher.js:21:10)
722 3927 at Object.Readdir.filterByType (/Users/medikoo/Projects/_packages/next/lib/fs/readdir.js:222:15)
723 3927 at Object.Readdir.filterByType (/Users/medikoo/Projects/_packages/next/lib/fs/readdir.js:236:15)
724 3927 at Object.self (/Users/medikoo/Projects/_packages/next/lib/fs/readdir.js:164:12)
725 3927 at Object.Readdir.readdir (/Users/medikoo/Projects/_packages/next/lib/fs/readdir.js:540:9)
726 3927 at Object.self (/Users/medikoo/Projects/_packages/next/lib/fs/readdir.js:164:21)
727 3729 at directory (/Users/medikoo/Projects/_packages/next/lib/fs/_watch-alt.js:95:2)
728 2820 at Readdir.filterIgnored.promise.root (/Users/medikoo/Projects/_packages/next/lib/fs/readdir.js:517:9)
729 2163 at basic (/Users/medikoo/Projects/_packages/next/lib/fs/is-gitrepo-root.js:14:8)
730 2159 at buildMap (/Users/medikoo/Projects/_packages/next/lib/fs/is-ignored.js:117:22)
731 2159 at Object.FindRoot (/Users/medikoo/Projects/_packages/next/lib/fs/find-root.js:18:15)
732 1107 at Readdir.filterIgnored.promise.root (/Users/medikoo/Projects/_packages/next/lib/fs/readdir.js:527:11)
733 697 at Object.Map.addPaths (/Users/medikoo/Projects/_packages/next/lib/fs/_get-conf-file-map.js:107:19)
734 697 at readFile (/Users/medikoo/Projects/_packages/next/lib/fs/read-file.js:18:8)
735 697 at Object.readRulesWatch (/Users/medikoo/Projects/_packages/next/lib/fs/_get-conf-file-map.js:45:12)
736 247 at module.exports (/Users/medikoo/Projects/_packages/next/lib/fs/_watch.js:90:2)
737 247 at module.exports (/Users/medikoo/Projects/_packages/next/lib/fs/_watch.js:90:13)
738 1 at Object.Readdir.init (/Users/medikoo/Projects/_packa
739 ```
740
741 **Using profiler significantly affects performance don't use it in production environment.**
742
743 ### Performance
744
745 Promises just by being rich objects introduce overhead over regular callbacks. If we do a lot asynchronous operations that are fast, performance of promise implementation that we rely on becomes a significant factor.
746
747 _benchmark_ folder contains two tests. Tests reflect real use case I had in which performance of promise implementation appeared to be crucial.
748
749 Base of a test is [lstat](http://nodejs.org/api/all.html#all_fs_lstat_path_callback) (fastest asynchronous call in node.js API), It's called 10000 times in parallel and sequentially.
750
751 _Note for benchmark purists: This test does real I/O, but there's no way to produce shim which will provide more reliable results (shim based on `setImmediate` adds more randomness to result than we got from calling real `lstat`)_
752
753 _Example output taken under Node v0.10.20 on 2008 MBP._
754
755 ```
756 Promise overhead (calling one after another) x10000:
757
758 1: 439ms Base (plain Node.js lstat call)
759 2: 461ms Kew: Dedicated wrapper
760 3: 609ms Bluebird: Dedicated wrapper
761 4: 614ms Bluebird: Promisify (generic wrapper)
762 5: 642ms Deferred: Dedicated wrapper
763 6: 720ms Deferred: Promisify (generic wrapper)
764 7: 792ms When: Dedicated wrapper
765 8: 1068ms Q: Dedicated wrapper
766 9: 1611ms Q: nbind (generic wrapper)
767
768 Promise overhead (concurrent calls) x10000:
769
770 1: 279ms Base (plain Node.js lstat call)
771 2: 293ms Bluebird: Promisify (generic wrapper)
772 3: 294ms Bluebird: Dedicated wrapper
773 4: 329ms Kew: Dedicated wrapper
774 5: 406ms When: Dedicated wrapper
775 6: 430ms Deferred: Dedicated wrapper
776 7: 598ms Deferred: Promisify (generic wrapper)
777 8: 683ms Deferred: Map + Promisify
778 9: 1610ms Q: Dedicated wrapper
779 10: 3645ms Q: nbind (generic wrapper)
780 ```
781
782 ### Tests
783
784 **Covered by over 300 unit tests**
785
786 $ npm test
787
788 ## Security contact information
789
790 To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure.
791
792 ---
793
794 <div align="center">
795 <b>
796 <a href="https://tidelift.com/subscription/pkg/npm-deferred?utm_source=npm-deferred&utm_medium=referral&utm_campaign=readme">Get professional support for d with a Tidelift subscription</a>
797 </b>
798 <br>
799 <sub>
800 Tidelift helps make open source sustainable for maintainers while giving companies<br>assurances about security, maintenance, and licensing for their dependencies.
801 </sub>
802 </div>
803
804 [semaphore-image]: https://semaphoreci.com/api/v1/medikoo-org/deferred/branches/master/badge.svg
805 [semaphore-url]: https://semaphoreci.com/medikoo-org/deferred
806 [appveyor-image]: https://img.shields.io/appveyor/ci/medikoo/deferred.svg
807 [appveyor-url]: https://ci.appveyor.com/project/medikoo/deferred
808 [codecov-image]: https://img.shields.io/codecov/c/github/medikoo/deferred.svg
809 [codecov-url]: https://codecov.io/gh/medikoo/deferred
810 [transpilation-image]: https://img.shields.io/badge/transpilation-free-brightgreen.svg
811 [npm-image]: https://img.shields.io/npm/v/deferred.svg
812 [npm-url]: https://www.npmjs.com/package/deferred