e1447bf5db54f1f261578566ec1fd78c93d8a9ee
[aai/esr-gui.git] /
1 <a href="http://promisesaplus.com/">
2     <img src="http://promisesaplus.com/assets/logo-small.png" alt="Promises/A+ logo"
3          title="Promises/A+ 1.1 compliant" align="right" />
4 </a>
5 [![Build Status](https://travis-ci.org/petkaantonov/bluebird.svg?branch=master)](https://travis-ci.org/petkaantonov/bluebird)
6 [![coverage-98%](http://img.shields.io/badge/coverage-98%-brightgreen.svg?style=flat)](http://petkaantonov.github.io/bluebird/coverage/debug/index.html)
7
8 **Got a question?** Join us on [stackoverflow](http://stackoverflow.com/questions/tagged/bluebird), the [mailing list](https://groups.google.com/forum/#!forum/bluebird-js) or chat on [IRC](https://webchat.freenode.net/?channels=#promises)
9
10 # Introduction
11
12 Bluebird is a fully featured [promise](#what-are-promises-and-why-should-i-use-them) library with focus on innovative features and performance
13
14
15
16 # Topics
17
18 - [Features](#features)
19 - [Quick start](#quick-start)
20 - [API Reference and examples](API.md)
21 - [Support](#support)
22 - [What are promises and why should I use them?](#what-are-promises-and-why-should-i-use-them)
23 - [Questions and issues](#questions-and-issues)
24 - [Error handling](#error-handling)
25 - [Development](#development)
26     - [Testing](#testing)
27     - [Benchmarking](#benchmarks)
28     - [Custom builds](#custom-builds)
29     - [For library authors](#for-library-authors)
30 - [What is the sync build?](#what-is-the-sync-build)
31 - [License](#license)
32 - [Snippets for common problems](https://github.com/petkaantonov/bluebird/wiki/Snippets)
33 - [Promise anti-patterns](https://github.com/petkaantonov/bluebird/wiki/Promise-anti-patterns)
34 - [Changelog](changelog.md)
35 - [Optimization guide](#optimization-guide)
36
37 # Features
38 <img src="http://petkaantonov.github.io/bluebird/logo.png" alt="bluebird logo" align="right" />
39
40 - [Promises A+](http://promisesaplus.com)
41 - [Synchronous inspection](API.md#synchronous-inspection)
42 - [Concurrency coordination](API.md#collections)
43 - [Promisification on steroids](API.md#promisification)
44 - [Resource management through a parallel of python `with`/C# `using`](API.md#resource-management)
45 - [Cancellation and timeouts](API.md#cancellation)
46 - [Parallel for C# `async` and `await`](API.md#generators)
47 - Mind blowing utilities such as
48     - [`.bind()`](API.md#binddynamic-thisarg---promise)
49     - [`.call()`](API.md#callstring-propertyname--dynamic-arg---promise)
50     - [`Promise.join()`](API.md#promisejoinpromisethenablevalue-promises-function-handler---promise)
51     - [And](API.md#core) [much](API.md#timers) [more](API.md#utility)!
52 - [Practical debugging solutions and sane defaults](#error-handling)
53 - [Sick performance](benchmark/)
54
55 <hr>
56
57 # Quick start
58
59 ## Node.js
60
61     npm install bluebird
62
63 Then:
64
65 ```js
66 var Promise = require("bluebird");
67 ```
68
69 ## Browsers
70
71 There are many ways to use bluebird in browsers:
72
73 - Direct downloads
74     - Full build [bluebird.js](https://cdn.jsdelivr.net/bluebird/latest/bluebird.js)
75     - Full build minified [bluebird.min.js](https://cdn.jsdelivr.net/bluebird/latest/bluebird.min.js)
76     - Core build [bluebird.core.js](https://cdn.jsdelivr.net/bluebird/latest/bluebird.core.js)
77     - Core build minified [bluebird.core.min.js](https://cdn.jsdelivr.net/bluebird/latest/bluebird.core.min.js)
78 - You may use browserify on the main export
79 - You may use the [bower](http://bower.io) package.
80
81 When using script tags the global variables `Promise` and `P` (alias for `Promise`) become available.
82
83 A [minimal bluebird browser build](#custom-builds) is &asymp;38.92KB minified*, 11.65KB gzipped and has no external dependencies.
84
85 *Google Closure Compiler using Simple.
86
87 #### Browser support
88
89 Browsers that [implement ECMA-262, edition 3](http://en.wikipedia.org/wiki/Ecmascript#Implementations) and later are supported.
90
91 [![Selenium Test Status](https://saucelabs.com/browser-matrix/petka_antonov.svg)](https://saucelabs.com/u/petka_antonov)
92
93 **Note** that in ECMA-262, edition 3 (IE7, IE8 etc.) it is not possible to use methods that have keyword names like `.catch` and `.finally`. The [API documentation](API.md) always lists a compatible alternative name that you can use if you need to support these browsers. For example `.catch` is replaced with `.caught` and `.finally` with `.lastly`.
94
95 Also, [long stack trace](API.md#promiselongstacktraces---void) support is only available in Chrome, Firefox and Internet Explorer 10+.
96
97 After quick start, see [API Reference and examples](API.md)
98
99 <hr>
100
101 # Support
102
103 - Mailing list: [bluebird-js@googlegroups.com](https://groups.google.com/forum/#!forum/bluebird-js)
104 - IRC: #promises @freenode
105 - StackOverflow: [bluebird tag](http://stackoverflow.com/questions/tagged/bluebird)
106 - Bugs and feature requests: [github issue tracker](https://github.com/petkaantonov/bluebird/issues?state=open)
107
108 <hr>
109
110 # What are promises and why should I use them?
111
112 You should use promises to turn this:
113
114 ```js
115 fs.readFile("file.json", function(err, val) {
116     if( err ) {
117         console.error("unable to read file");
118     }
119     else {
120         try {
121             val = JSON.parse(val);
122             console.log(val.success);
123         }
124         catch( e ) {
125             console.error("invalid json in file");
126         }
127     }
128 });
129 ```
130
131 Into this:
132
133 ```js
134 fs.readFileAsync("file.json").then(JSON.parse).then(function(val) {
135     console.log(val.success);
136 })
137 .catch(SyntaxError, function(e) {
138     console.error("invalid json in file");
139 })
140 .catch(function(e) {
141     console.error("unable to read file");
142 });
143 ```
144
145 *If you are wondering "there is no `readFileAsync` method on `fs` that returns a promise", see [promisification](API.md#promisification)*
146
147 Actually you might notice the latter has a lot in common with code that would do the same using synchronous I/O:
148
149 ```js
150 try {
151     var val = JSON.parse(fs.readFileSync("file.json"));
152     console.log(val.success);
153 }
154 //Syntax actually not supported in JS but drives the point
155 catch(SyntaxError e) {
156     console.error("invalid json in file");
157 }
158 catch(Error e) {
159     console.error("unable to read file");
160 }
161 ```
162
163 And that is the point - being able to have something that is a lot like `return` and `throw` in synchronous code.
164
165 You can also use promises to improve code that was written with callback helpers:
166
167
168 ```js
169 //Copyright Plato http://stackoverflow.com/a/19385911/995876
170 //CC BY-SA 2.5
171 mapSeries(URLs, function (URL, done) {
172     var options = {};
173     needle.get(URL, options, function (error, response, body) {
174         if (error) {
175             return done(error);
176         }
177         try {
178             var ret = JSON.parse(body);
179             return done(null, ret);
180         }
181         catch (e) {
182             done(e);
183         }
184     });
185 }, function (err, results) {
186     if (err) {
187         console.log(err);
188     } else {
189         console.log('All Needle requests successful');
190         // results is a 1 to 1 mapping in order of URLs > needle.body
191         processAndSaveAllInDB(results, function (err) {
192             if (err) {
193                 return done(err);
194             }
195             console.log('All Needle requests saved');
196             done(null);
197         });
198     }
199 });
200 ```
201
202 Is more pleasing to the eye when done with promises:
203
204 ```js
205 Promise.promisifyAll(needle);
206 var options = {};
207
208 var current = Promise.resolve();
209 Promise.map(URLs, function(URL) {
210     current = current.then(function () {
211         return needle.getAsync(URL, options);
212     });
213     return current;
214 }).map(function(responseAndBody){
215     return JSON.parse(responseAndBody[1]);
216 }).then(function (results) {
217     return processAndSaveAllInDB(results);
218 }).then(function(){
219     console.log('All Needle requests saved');
220 }).catch(function (e) {
221     console.log(e);
222 });
223 ```
224
225 Also promises don't just give you correspondences for synchronous features but can also be used as limited event emitters or callback aggregators.
226
227 More reading:
228
229  - [Promise nuggets](https://promise-nuggets.github.io/)
230  - [Why I am switching to promises](http://spion.github.io/posts/why-i-am-switching-to-promises.html)
231  - [What is the the point of promises](http://domenic.me/2012/10/14/youre-missing-the-point-of-promises/#toc_1)
232  - [Snippets for common problems](https://github.com/petkaantonov/bluebird/wiki/Snippets)
233  - [Promise anti-patterns](https://github.com/petkaantonov/bluebird/wiki/Promise-anti-patterns)
234
235 # Questions and issues
236
237 The [github issue tracker](https://github.com/petkaantonov/bluebird/issues) is **_only_** for bug reports and feature requests. Anything else, such as questions for help in using the library, should be posted in [StackOverflow](http://stackoverflow.com/questions/tagged/bluebird) under tags `promise` and `bluebird`.
238
239 # Error handling
240
241 This is a problem every promise library needs to handle in some way. Unhandled rejections/exceptions don't really have a good agreed-on asynchronous correspondence. The problem is that it is impossible to predict the future and know if a rejected promise will eventually be handled.
242
243 There are two common pragmatic attempts at solving the problem that promise libraries do.
244
245 The more popular one is to have the user explicitly communicate that they are done and any unhandled rejections should be thrown, like so:
246
247 ```js
248 download().then(...).then(...).done();
249 ```
250
251 For handling this problem, in my opinion, this is completely unacceptable and pointless. The user must remember to explicitly call `.done` and that cannot be justified when the problem is forgetting to create an error handler in the first place.
252
253 The second approach, which is what bluebird by default takes, is to call a registered handler if a rejection is unhandled by the start of a second turn. The default handler is to write the stack trace to `stderr` or `console.error` in browsers. This is close to what happens with synchronous code - your code doesn't work as expected and you open console and see a stack trace. Nice.
254
255 Of course this is not perfect, if your code for some reason needs to swoop in and attach error handler to some promise after the promise has been hanging around a while then you will see annoying messages. In that case you can use the `.done()` method to signal that any hanging exceptions should be thrown.
256
257 If you want to override the default handler for these possibly unhandled rejections, you can pass yours like so:
258
259 ```js
260 Promise.onPossiblyUnhandledRejection(function(error){
261     throw error;
262 });
263 ```
264
265 If you want to also enable long stack traces, call:
266
267 ```js
268 Promise.longStackTraces();
269 ```
270
271 right after the library is loaded.
272
273 In node.js use the environment flag `BLUEBIRD_DEBUG`:
274
275 ```
276 BLUEBIRD_DEBUG=1 node server.js
277 ```
278
279 to enable long stack traces in all instances of bluebird.
280
281 Long stack traces cannot be disabled after being enabled, and cannot be enabled after promises have already been created. Long stack traces imply a substantial performance penalty, even after using every trick to optimize them.
282
283 Long stack traces are enabled by default in the debug build.
284
285 #### Expected and unexpected errors
286
287 A practical problem with Promises/A+ is that it models Javascript `try-catch` too closely for its own good. Therefore by default promises inherit `try-catch` warts such as the inability to specify the error types that the catch block is eligible for. It is an anti-pattern in every other language to use catch-all handlers because they swallow exceptions that you might not know about.
288
289 Now, Javascript does have a perfectly fine and working way of creating error type hierarchies. It is still quite awkward to use them with the built-in `try-catch` however:
290
291 ```js
292 try {
293     //code
294 }
295 catch(e) {
296     if( e instanceof WhatIWantError) {
297         //handle
298     }
299     else {
300         throw e;
301     }
302 }
303 ```
304
305 Without such checking, unexpected errors would be silently swallowed. However, with promises, bluebird brings the future (hopefully) here now and extends the `.catch` to [accept potential error type eligibility](API.md#catchfunction-errorclass-function-handler---promise).
306
307 For instance here it is expected that some evil or incompetent entity will try to crash our server from `SyntaxError` by providing syntactically invalid JSON:
308
309 ```js
310 getJSONFromSomewhere().then(function(jsonString) {
311     return JSON.parse(jsonString);
312 }).then(function(object) {
313     console.log("it was valid json: ", object);
314 }).catch(SyntaxError, function(e){
315     console.log("don't be evil");
316 });
317 ```
318
319 Here any kind of unexpected error will be automatically reported on `stderr` along with a stack trace because we only register a handler for the expected `SyntaxError`.
320
321 Ok, so, that's pretty neat. But actually not many libraries define error types and it is in fact a complete ghetto out there with ad hoc strings being attached as some arbitrary property name like `.name`, `.type`, `.code`, not having any property at all or even throwing strings as errors and so on. So how can we still listen for expected errors?
322
323 Bluebird defines a special error type `OperationalError` (you can get a reference from `Promise.OperationalError`). This type of error is given as rejection reason by promisified methods when
324 their underlying library gives an untyped, but expected error. Primitives such as strings, and error objects that are directly created like `new Error("database didn't respond")` are considered untyped.
325
326 Example of such library is the node core library `fs`. So if we promisify it, we can catch just the errors we want pretty easily and have programmer errors be redirected to unhandled rejection handler so that we notice them:
327
328 ```js
329 //Read more about promisification in the API Reference:
330 //API.md
331 var fs = Promise.promisifyAll(require("fs"));
332
333 fs.readFileAsync("myfile.json").then(JSON.parse).then(function (json) {
334     console.log("Successful json");
335 }).catch(SyntaxError, function (e) {
336     console.error("file contains invalid json");
337 }).catch(Promise.OperationalError, function (e) {
338     console.error("unable to read file, because: ", e.message);
339 });
340 ```
341
342 The last `catch` handler is only invoked when the `fs` module explicitly used the `err` argument convention of async callbacks to inform of an expected error. The `OperationalError` instance will contain the original error in its `.cause` property but it does have a direct copy of the `.message` and `.stack` too. In this code any unexpected error - be it in our code or the `fs` module - would not be caught by these handlers and therefore not swallowed.
343
344 Since a `catch` handler typed to `Promise.OperationalError` is expected to be used very often, it has a neat shorthand:
345
346 ```js
347 .error(function (e) {
348     console.error("unable to read file, because: ", e.message);
349 });
350 ```
351
352 See [API documentation for `.error()`](API.md#error-rejectedhandler----promise)
353
354 Finally, Bluebird also supports predicate-based filters. If you pass a
355 predicate function instead of an error type, the predicate will receive
356 the error as an argument. The return result will be used to determine whether
357 the error handler should be called.
358
359 Predicates should allow for very fine grained control over caught errors:
360 pattern matching, error typesets with set operations and many other techniques
361 can be implemented on top of them.
362
363 Example of using a predicate-based filter:
364
365 ```js
366 var Promise = require("bluebird");
367 var request = Promise.promisify(require("request"));
368
369 function clientError(e) {
370     return e.code >= 400 && e.code < 500;
371 }
372
373 request("http://www.google.com").then(function(contents){
374     console.log(contents);
375 }).catch(clientError, function(e){
376    //A client error like 400 Bad Request happened
377 });
378 ```
379
380 **Danger:** The JavaScript language allows throwing primitive values like strings. Throwing primitives can lead to worse or no stack traces. Primitives [are not exceptions](http://www.devthought.com/2011/12/22/a-string-is-not-an-error/). You should consider always throwing Error objects when handling exceptions.
381
382 <hr>
383
384 #### How do long stack traces differ from e.g. Q?
385
386 Bluebird attempts to have more elaborate traces. Consider:
387
388 ```js
389 Error.stackTraceLimit = 25;
390 Q.longStackSupport = true;
391 Q().then(function outer() {
392     return Q().then(function inner() {
393         return Q().then(function evenMoreInner() {
394             a.b.c.d();
395         }).catch(function catcher(e){
396             console.error(e.stack);
397         });
398     })
399 });
400 ```
401
402 You will see
403
404     ReferenceError: a is not defined
405         at evenMoreInner (<anonymous>:7:13)
406     From previous event:
407         at inner (<anonymous>:6:20)
408
409 Compare to:
410
411 ```js
412 Error.stackTraceLimit = 25;
413 Promise.longStackTraces();
414 Promise.resolve().then(function outer() {
415     return Promise.resolve().then(function inner() {
416         return Promise.resolve().then(function evenMoreInner() {
417             a.b.c.d();
418         }).catch(function catcher(e){
419             console.error(e.stack);
420         });
421     });
422 });
423 ```
424
425     ReferenceError: a is not defined
426         at evenMoreInner (<anonymous>:7:13)
427     From previous event:
428         at inner (<anonymous>:6:36)
429     From previous event:
430         at outer (<anonymous>:5:32)
431     From previous event:
432         at <anonymous>:4:21
433         at Object.InjectedScript._evaluateOn (<anonymous>:572:39)
434         at Object.InjectedScript._evaluateAndWrap (<anonymous>:531:52)
435         at Object.InjectedScript.evaluate (<anonymous>:450:21)
436
437
438 A better and more practical example of the differences can be seen in gorgikosev's [debuggability competition](https://github.com/spion/async-compare#debuggability).
439
440 <hr>
441
442 # Development
443
444 For development tasks such as running benchmarks or testing, you need to clone the repository and install dev-dependencies.
445
446 Install [node](http://nodejs.org/) and [npm](https://npmjs.org/)
447
448     git clone git@github.com:petkaantonov/bluebird.git
449     cd bluebird
450     npm install
451
452 ## Testing
453
454 To run all tests, run
455
456     node tools/test
457
458 If you need to run generator tests run the `tool/test.js` script with `--harmony` argument and node 0.11+:
459
460     node-dev --harmony tools/test
461
462 You may specify an individual test file to run with the `--run` script flag:
463
464     node tools/test --run=cancel.js
465
466
467 This enables output from the test and may give a better idea where the test is failing. The parameter to `--run` can be any file name located in `test/mocha` folder.
468
469 #### Testing in browsers
470
471 To run the test in a browser instead of node, pass the flag `--browser` to the test tool
472
473     node tools/test --run=cancel.js --browser
474
475 This will automatically create a server (default port 9999) and open it in your default browser once the tests have been compiled.
476
477 Keep the test tab active because some tests are timing-sensitive and will fail if the browser is throttling timeouts. Chrome will do this for example when the tab is not active.
478
479 #### Supported options by the test tool
480
481 The value of boolean flags is determined by presence, if you want to pass false value for a boolean flag, use the `no-`-prefix e.g. `--no-browser`.
482
483  - `--run=String` - Which tests to run (or compile when testing in browser). Default `"all"`. Can also be a glob string (relative to ./test/mocha folder).
484  - `--cover=String`. Create code coverage using the String as istanbul reporter. Coverage is created in the ./coverage folder. No coverage is created by default, default reporter is `"html"` (use `--cover` to use default reporter).
485  - `--browser` - Whether to compile tests for browsers. Default `false`.
486  - `--port=Number` - Port where local server is hosted when testing in browser. Default `9999`
487  - `--execute-browser-tests` - Whether to execute the compiled tests for browser when using `--browser`. Default `true`.
488  - `--open-browser` - Whether to open the default browser when executing browser tests. Default `true`.
489  - `--fake-timers` - Whether to use fake timers (`setTimeout` etc) when running tests in node. Default `true`.
490  - `--js-hint` - Whether to run JSHint on source files. Default `true`.
491  - `--saucelabs` - Whether to create a tunnel to sauce labs and run tests in their VMs instead of your browser when compiling tests for browser. Default `false`.
492
493 ## Benchmarks
494
495 To run a benchmark, run the given command for a benchmark while on the project root. Requires bash (on windows the mingw32 that comes with git works fine too).
496
497 Node 0.11.2+ is required to run the generator examples.
498
499 ### 1\. DoxBee sequential
500
501 Currently the most relevant benchmark is @gorkikosev's benchmark in the article [Analysis of generators and other async patterns in node](http://spion.github.io/posts/analysis-generators-and-other-async-patterns-node.html). The benchmark emulates a situation where n amount of users are making a request in parallel to execute some mixed async/sync action. The benchmark has been modified to include a warm-up phase to minimize any JITing during timed sections.
502
503 Command: `bench doxbee`
504
505 ### 2\. Made-up parallel
506
507 This made-up scenario runs 15 shimmed queries in parallel.
508
509 Command: `bench parallel`
510
511 ## Custom builds
512
513 Custom builds for browsers are supported through a command-line utility.
514
515
516 <table>
517     <caption>The following features can be disabled</caption>
518     <thead>
519         <tr>
520             <th>Feature(s)</th>
521             <th>Command line identifier</th>
522         </tr>
523     </thead>
524     <tbody>
525
526         <tr><td><a href="API.md#any---promise"><code>.any</code></a> and <a href="API.md#promiseanyarraydynamicpromise-values---promise"><code>Promise.any</code></a></td><td><code>any</code></td></tr>
527         <tr><td><a href="API.md#race---promise"><code>.race</code></a> and <a href="API.md#promiseracearraypromise-promises---promise"><code>Promise.race</code></a></td><td><code>race</code></td></tr>
528         <tr><td><a href="API.md#callstring-propertyname--dynamic-arg---promise"><code>.call</code></a> and <a href="API.md#getstring-propertyname---promise"><code>.get</code></a></td><td><code>call_get</code></td></tr>
529         <tr><td><a href="API.md#filterfunction-filterer---promise"><code>.filter</code></a> and <a href="API.md#promisefilterarraydynamicpromise-values-function-filterer---promise"><code>Promise.filter</code></a></td><td><code>filter</code></td></tr>
530         <tr><td><a href="API.md#mapfunction-mapper---promise"><code>.map</code></a> and <a href="API.md#promisemaparraydynamicpromise-values-function-mapper---promise"><code>Promise.map</code></a></td><td><code>map</code></td></tr>
531         <tr><td><a href="API.md#reducefunction-reducer--dynamic-initialvalue---promise"><code>.reduce</code></a> and <a href="API.md#promisereducearraydynamicpromise-values-function-reducer--dynamic-initialvalue---promise"><code>Promise.reduce</code></a></td><td><code>reduce</code></td></tr>
532         <tr><td><a href="API.md#props---promise"><code>.props</code></a> and <a href="API.md#promisepropsobjectpromise-object---promise"><code>Promise.props</code></a></td><td><code>props</code></td></tr>
533         <tr><td><a href="API.md#settle---promise"><code>.settle</code></a> and <a href="API.md#promisesettlearraydynamicpromise-values---promise"><code>Promise.settle</code></a></td><td><code>settle</code></td></tr>
534         <tr><td><a href="API.md#someint-count---promise"><code>.some</code></a> and <a href="API.md#promisesomearraydynamicpromise-values-int-count---promise"><code>Promise.some</code></a></td><td><code>some</code></td></tr>
535         <tr><td><a href="API.md#nodeifyfunction-callback---promise"><code>.nodeify</code></a></td><td><code>nodeify</code></td></tr>
536         <tr><td><a href="API.md#promisecoroutinegeneratorfunction-generatorfunction---function"><code>Promise.coroutine</code></a> and <a href="API.md#promisespawngeneratorfunction-generatorfunction---promise"><code>Promise.spawn</code></a></td><td><code>generators</code></td></tr>
537         <tr><td><a href="API.md#progression">Progression</a></td><td><code>progress</code></td></tr>
538         <tr><td><a href="API.md#promisification">Promisification</a></td><td><code>promisify</code></td></tr>
539         <tr><td><a href="API.md#cancellation">Cancellation</a></td><td><code>cancel</code></td></tr>
540         <tr><td><a href="API.md#timers">Timers</a></td><td><code>timers</code></td></tr>
541         <tr><td><a href="API.md#resource-management">Resource management</a></td><td><code>using</code></td></tr>
542
543     </tbody>
544 </table>
545
546
547 Make sure you have cloned the repo somewhere and did `npm install` successfully.
548
549 After that you can run:
550
551     node tools/build --features="core"
552
553
554 The above builds the most minimal build you can get. You can add more features separated by spaces from the above list:
555
556     node tools/build --features="core filter map reduce"
557
558 The custom build file will be found from `/js/browser/bluebird.js`. It will have a comment that lists the disabled and enabled features.
559
560 Note that the build leaves the `/js/main` etc folders with same features so if you use the folder for node.js at the same time, don't forget to build
561 a full version afterwards (after having taken a copy of the bluebird.js somewhere):
562
563     node tools/build --debug --main --zalgo --browser --minify
564
565 #### Supported options by the build tool
566
567 The value of boolean flags is determined by presence, if you want to pass false value for a boolean flag, use the `no-`-prefix e.g. `--no-debug`.
568
569  - `--main` - Whether to build the main build. The main build is placed at `js/main` directory. Default `false`.
570  - `--debug` - Whether to build the debug build. The debug build is placed at `js/debug` directory. Default `false`.
571  - `--zalgo` - Whether to build the zalgo build. The zalgo build is placed at `js/zalgo` directory. Default `false`.
572  - `--browser` - Whether to compile the browser build. The browser build file is placed at `js/browser/bluebird.js` Default `false`.
573  - `--minify` - Whether to minify the compiled browser build. The minified browser build file is placed at `js/browser/bluebird.min.js` Default `true`.
574  - `--features=String` - See [custom builds](#custom-builds)
575
576 <hr>
577
578 ## For library authors
579
580 Building a library that depends on bluebird? You should know about a few features.
581
582 If your library needs to do something obtrusive like adding or modifying methods on the `Promise` prototype, uses long stack traces or uses a custom unhandled rejection handler then... that's totally ok as long as you don't use `require("bluebird")`. Instead you should create a file
583 that creates an isolated copy. For example, creating a file called `bluebird-extended.js` that contains:
584
585 ```js
586                 //NOTE the function call right after
587 module.exports = require("bluebird/js/main/promise")();
588 ```
589
590 Your library can then use `var Promise = require("bluebird-extended");` and do whatever it wants with it. Then if the application or other library uses their own bluebird promises they will all play well together because of Promises/A+ thenable assimilation magic.
591
592 You should also know about [`.nodeify()`](API.md#nodeifyfunction-callback---promise) which makes it easy to provide a dual callback/promise API.
593
594 <hr>
595
596 ## What is the sync build?
597
598 You may now use sync build by:
599
600     var Promise = require("bluebird/zalgo");
601
602 The sync build is provided to see how forced asynchronity affects benchmarks. It should not be used in real code due to the implied hazards.
603
604 The normal async build gives Promises/A+ guarantees about asynchronous resolution of promises. Some people think this affects performance or just plain love their code having a possibility
605 of stack overflow errors and non-deterministic behavior.
606
607 The sync build skips the async call trampoline completely, e.g code like:
608
609     async.invoke( this.fn, this, val );
610
611 Appears as this in the sync build:
612
613     this.fn(val);
614
615 This should pressure the CPU slightly less and thus the sync build should perform better. Indeed it does, but only marginally. The biggest performance boosts are from writing efficient Javascript, not from compromising determinism.
616
617 Note that while some benchmarks are waiting for the next event tick, the CPU is actually not in use during that time. So the resulting benchmark result is not completely accurate because on node.js you only care about how much the CPU is taxed. Any time spent on CPU is time the whole process (or server) is paralyzed. And it is not graceful like it would be with threads.
618
619
620 ```js
621 var cache = new Map(); //ES6 Map or DataStructures/Map or whatever...
622 function getResult(url) {
623     var resolver = Promise.pending();
624     if (cache.has(url)) {
625         resolver.resolve(cache.get(url));
626     }
627     else {
628         http.get(url, function(err, content) {
629             if (err) resolver.reject(err);
630             else {
631                 cache.set(url, content);
632                 resolver.resolve(content);
633             }
634         });
635     }
636     return resolver.promise;
637 }
638
639
640
641 //The result of console.log is truly random without async guarantees
642 function guessWhatItPrints( url ) {
643     var i = 3;
644     getResult(url).then(function(){
645         i = 4;
646     });
647     console.log(i);
648 }
649 ```
650
651 # Optimization guide
652
653 Articles about optimization will be periodically posted in [the wiki section](https://github.com/petkaantonov/bluebird/wiki), polishing edits are welcome.
654
655 A single cohesive guide compiled from the articles will probably be done eventually.
656
657 # License
658
659 The MIT License (MIT)
660
661 Copyright (c) 2014 Petka Antonov
662
663 Permission is hereby granted, free of charge, to any person obtaining a copy
664 of this software and associated documentation files (the "Software"), to deal
665 in the Software without restriction, including without limitation the rights
666 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
667 copies of the Software, and to permit persons to whom the Software is
668 furnished to do so, subject to the following conditions:
669
670 The above copyright notice and this permission notice shall be included in
671 all copies or substantial portions of the Software.
672
673 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
674 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
675 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
676 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
677 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
678 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
679 THE SOFTWARE.