Changeset 489


Ignore:
Timestamp:
03/08/14 11:41:10 (11 years ago)
Author:
hendrikvanantwerpen
Message:

Update node modules

Location:
Dev/trunk/src
Files:
34 added
43 edited

Legend:

Unmodified
Added
Removed
  • Dev/trunk/src/node_modules/express/node_modules/commander/package.json

    r487 r489  
    3636  "homepage": "https://github.com/visionmedia/commander.js",
    3737  "_id": "commander@0.6.1",
    38   "dist": {
    39     "shasum": "c725ed5e9b2bf532b3fe3cba4f81b552cecf0550"
    40   },
    41   "_from": "commander@0.6.1",
    42   "_resolved": "https://registry.npmjs.org/commander/-/commander-0.6.1.tgz"
     38  "_from": "commander@0.6.1"
    4339}
  • Dev/trunk/src/node_modules/express/node_modules/connect/node_modules/bytes/package.json

    r487 r489  
    1717  "readmeFilename": "Readme.md",
    1818  "_id": "bytes@0.2.0",
    19   "dist": {
    20     "shasum": "b4c569295d86a498a119945f1d8a26f76e4b5462"
    21   },
    22   "_from": "bytes@0.2.0",
    23   "_resolved": "https://registry.npmjs.org/bytes/-/bytes-0.2.0.tgz"
     19  "_from": "bytes@0.2.0"
    2420}
  • Dev/trunk/src/node_modules/express/node_modules/connect/node_modules/cookie/package.json

    r487 r489  
    3434  "homepage": "https://github.com/shtylman/node-cookie",
    3535  "_id": "cookie@0.0.5",
    36   "dist": {
    37     "shasum": "2597397e06ec3eaf53c88851570e97949c1e4dcd"
    38   },
    39   "_from": "cookie@0.0.5",
    40   "_resolved": "https://registry.npmjs.org/cookie/-/cookie-0.0.5.tgz"
     36  "_from": "cookie@0.0.5"
    4137}
  • Dev/trunk/src/node_modules/express/node_modules/connect/node_modules/pause/package.json

    r487 r489  
    1717  "readmeFilename": "Readme.md",
    1818  "_id": "pause@0.0.1",
    19   "dist": {
    20     "shasum": "dc3b2287742f3f6249f2d228e74cff5a3f9fe8da"
    21   },
    2219  "_from": "pause@0.0.1",
    23   "_resolved": "https://registry.npmjs.org/pause/-/pause-0.0.1.tgz"
     20  "scripts": {}
    2421}
  • Dev/trunk/src/node_modules/express/node_modules/connect/node_modules/send/node_modules/mime/package.json

    r487 r489  
    3333  "homepage": "https://github.com/broofa/node-mime",
    3434  "_id": "mime@1.2.11",
    35   "_from": "mime@~1.2.9"
     35  "_from": "mime@~1.2.9",
     36  "scripts": {}
    3637}
  • Dev/trunk/src/node_modules/express/node_modules/connect/node_modules/send/package.json

    r487 r489  
    3939  "homepage": "https://github.com/visionmedia/send",
    4040  "_id": "send@0.1.1",
    41   "dist": {
    42     "shasum": "40ded726322604c29d7229683f9207bd6d76e217"
    43   },
    44   "_from": "send@0.1.1",
    45   "_resolved": "https://registry.npmjs.org/send/-/send-0.1.1.tgz"
     41  "_from": "send@0.1.1"
    4642}
  • Dev/trunk/src/node_modules/express/node_modules/cookie/package.json

    r487 r489  
    3434  "homepage": "https://github.com/shtylman/node-cookie",
    3535  "_id": "cookie@0.1.0",
    36   "dist": {
    37     "shasum": "b56ac6108fcab9073208d405c4fa8aaa35f00810"
    38   },
    39   "_from": "cookie@0.1.0",
    40   "_resolved": "https://registry.npmjs.org/cookie/-/cookie-0.1.0.tgz"
     36  "_from": "cookie@0.1.0"
    4137}
  • Dev/trunk/src/node_modules/express/node_modules/fresh/package.json

    r487 r489  
    1717  "readmeFilename": "Readme.md",
    1818  "_id": "fresh@0.1.0",
    19   "dist": {
    20     "shasum": "97ce63fda273b033f866d3a29b9920d034aa2074"
    21   },
    22   "_from": "fresh@0.1.0",
    23   "_resolved": "https://registry.npmjs.org/fresh/-/fresh-0.1.0.tgz"
     19  "_from": "fresh@0.1.0"
    2420}
  • Dev/trunk/src/node_modules/express/node_modules/methods/package.json

    r487 r489  
    1717  "readme": "ERROR: No README data found!",
    1818  "_id": "methods@0.0.1",
    19   "dist": {
    20     "shasum": "c0a484b3e1f28764c5cfd234e1a156d47092ecca"
    21   },
    22   "_from": "methods@0.0.1",
    23   "_resolved": "https://registry.npmjs.org/methods/-/methods-0.0.1.tgz"
     19  "_from": "methods@0.0.1"
    2420}
  • Dev/trunk/src/node_modules/express/node_modules/mkdirp/package.json

    r487 r489  
    3434  "homepage": "https://github.com/substack/node-mkdirp",
    3535  "_id": "mkdirp@0.3.4",
    36   "dist": {
    37     "shasum": "8642eb45b73f5cd19824e94b572871013af8a305"
    38   },
    39   "_from": "mkdirp@0.3.4",
    40   "_resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.3.4.tgz"
     36  "_from": "mkdirp@0.3.4"
    4137}
  • Dev/trunk/src/node_modules/express/node_modules/range-parser/package.json

    r487 r489  
    1717  "readmeFilename": "Readme.md",
    1818  "_id": "range-parser@0.0.4",
    19   "dist": {
    20     "shasum": "a91c03c737187765f0dcdbe32fa824e52b47a9a6"
    21   },
    22   "_from": "range-parser@0.0.4",
    23   "_resolved": "https://registry.npmjs.org/range-parser/-/range-parser-0.0.4.tgz"
     19  "_from": "range-parser@0.0.4"
    2420}
  • Dev/trunk/src/node_modules/express/package.json

    r487 r489  
    8282  "homepage": "https://github.com/visionmedia/express",
    8383  "_id": "express@3.2.6",
    84   "dist": {
    85     "shasum": "4e16430ceaf29ac1f185c6996d50ca6394ec6357"
    86   },
    87   "_from": "express@3.2.6",
    88   "_resolved": "https://registry.npmjs.org/express/-/express-3.2.6.tgz"
     84  "_from": "express@3.2.6"
    8985}
  • Dev/trunk/src/node_modules/passport-local/node_modules/pkginfo/package.json

    r484 r489  
    3131    "url": "https://github.com/indexzero/node-pkginfo/issues"
    3232  },
     33  "homepage": "https://github.com/indexzero/node-pkginfo",
    3334  "_id": "pkginfo@0.2.3",
    34   "_from": "pkginfo@0.2.x"
     35  "dist": {
     36    "shasum": "58124620563fa62cb389f5f82323c6089d5033a4"
     37  },
     38  "_from": "pkginfo@0.2.3",
     39  "_resolved": "https://registry.npmjs.org/pkginfo/-/pkginfo-0.2.3.tgz"
    3540}
  • Dev/trunk/src/node_modules/passport-local/package.json

    r484 r489  
    2121  },
    2222  "devDependencies": {
    23     "vows": "0.6.x"
     23    "vows": "0.6.x",
     24    "pkginfo": "^0.2.3",
     25    "passport": "^0.1.18"
    2426  },
    2527  "scripts": {
  • Dev/trunk/src/node_modules/passport/.travis.yml

    r484 r489  
    11language: "node_js"
    22node_js:
    3   - 0.4
    4   - 0.6
    5   - 0.8
     3  - "0.4"
     4  - "0.6"
     5  - "0.8"
     6  - "0.10"
  • Dev/trunk/src/node_modules/passport/README.md

    r484 r489  
    1414
    1515    $ npm install passport
     16
     17###### Donate
     18
     19Using Passport in your project?  [Donations](https://www.gittip.com/jaredhanson/)
     20are greatly appreciated and help support development of this and other quality
     21modules.
    1622
    1723## Usage
     
    8692      });
    8793
    88 ## Examples
    89 
    90 For a complete, working example, refer to the [login example](https://github.com/jaredhanson/passport-local/tree/master/examples/login)
    91 included in [passport-local](https://github.com/jaredhanson/passport-local).
    92 
    9394## Strategies
    9495
    95 Passport has a comprehensive set of **over 120** authentication strategies
     96Passport has a comprehensive set of **over 140** authentication strategies
    9697covering social networking, enterprise integration, API services, and more.
    9798The [complete list](https://github.com/jaredhanson/passport/wiki/Strategies) is
     
    109110|[Google](https://github.com/jaredhanson/passport-google-oauth) | OAuth / OAuth 2.0        |[Jared Hanson](https://github.com/jaredhanson)  |
    110111|[Twitter](https://github.com/jaredhanson/passport-twitter)     | OAuth                    |[Jared Hanson](https://github.com/jaredhanson)  |
     112
     113## Examples
     114
     115- For a complete, working example, refer to the [login example](https://github.com/jaredhanson/passport-local/tree/master/examples/login)
     116included in [passport-local](https://github.com/jaredhanson/passport-local).
     117- Please refer to this [tutorial](http://mherman.org/blog/2013/11/10/social-authentication-with-passport-dot-js/) on setting up various social authentication strategies, including a working example found on this [repo](https://github.com/mjhea0/passport-examples).
    111118
    112119## Related Modules
  • Dev/trunk/src/node_modules/passport/lib/passport/index.js

    r484 r489  
    236236 */
    237237Passport.prototype.authorize = function(strategy, options, callback) {
     238  var fwAuthorize = this._framework && (this._framework.authorize || this._framework.authenticate);
     239
    238240  options = options || {};
    239241  options.assignProperty = 'account';
     242
     243  if (fwAuthorize) {
     244    return fwAuthorize(strategy, options, callback).bind(this);
     245  }
    240246 
    241247  return authenticate(strategy, options, callback).bind(this);
  • Dev/trunk/src/node_modules/passport/node_modules/pause/package.json

    r484 r489  
    1717  "readmeFilename": "Readme.md",
    1818  "_id": "pause@0.0.1",
    19   "dist": {
    20     "shasum": "dc3b2287742f3f6249f2d228e74cff5a3f9fe8da"
    21   },
    22   "_from": "pause@0.0.1",
    23   "_resolved": "https://registry.npmjs.org/pause/-/pause-0.0.1.tgz"
     19  "_from": "pause@0.0.1"
    2420}
  • Dev/trunk/src/node_modules/passport/node_modules/pkginfo/package.json

    r484 r489  
    3131    "url": "https://github.com/indexzero/node-pkginfo/issues"
    3232  },
     33  "homepage": "https://github.com/indexzero/node-pkginfo",
    3334  "_id": "pkginfo@0.2.3",
    3435  "dist": {
  • Dev/trunk/src/node_modules/passport/package.json

    r484 r489  
    11{
    22  "name": "passport",
    3   "version": "0.1.17",
     3  "version": "0.1.18",
    44  "description": "Simple, unobtrusive authentication for Node.js.",
    55  "keywords": [
     
    3535  },
    3636  "devDependencies": {
    37     "vows": "0.6.x"
     37    "vows": "~0.7.0"
    3838  },
    3939  "scripts": {
     
    4343    "node": ">= 0.4.0"
    4444  },
    45   "readme": "# Passport\n\nPassport is [Express](http://expressjs.com/)-compatible authentication\nmiddleware for [Node.js](http://nodejs.org/).\n\nPassport's sole purpose is to authenticate requests, which it does through an\nextensible set of plugins known as _strategies_.  Passport does not mount\nroutes or assume any particular database schema, which maximizes flexiblity and\nallows application-level decisions to be made by the developer.  The API is\nsimple: you provide Passport a request to authenticate, and Passport provides\nhooks for controlling what occurs when authentication succeeds or fails.\n\n## Install\n\n    $ npm install passport\n\n## Usage\n\n#### Strategies\n\nPassport uses the concept of strategies to authenticate requests.  Strategies\ncan range from verifying username and password credentials, delegated\nauthentication using [OAuth](http://oauth.net/) (for example, via [Facebook](http://www.facebook.com/)\nor [Twitter](http://twitter.com/)), or federated authentication using [OpenID](http://openid.net/).\n\nBefore authenticating requests, the strategy (or strategies) used by an\napplication must be configured.\n\n    passport.use(new LocalStrategy(\n      function(username, password, done) {\n        User.findOne({ username: username, password: password }, function (err, user) {\n          done(err, user);\n        });\n      }\n    ));\n\n#### Sessions\n\nPassport will maintain persistent login sessions.  In order for persistent\nsessions to work, the authenticated user must be serialized to the session, and\ndeserialized when subsequent requests are made.\n\nPassport does not impose any restrictions on how your user records are stored.\nInstead, you provide functions to Passport which implements the necessary\nserialization and deserialization logic.  In a typical application, this will be\nas simple as serializing the user ID, and finding the user by ID when\ndeserializing.\n\n    passport.serializeUser(function(user, done) {\n      done(null, user.id);\n    });\n\n    passport.deserializeUser(function(id, done) {\n      User.findById(id, function (err, user) {\n        done(err, user);\n      });\n    });\n\n#### Middleware\n\nTo use Passport in an [Express](http://expressjs.com/) or\n[Connect](http://senchalabs.github.com/connect/)-based application, configure it\nwith the required `passport.initialize()` middleware.  If your application uses\npersistent login sessions (recommended, but not required), `passport.session()`\nmiddleware must also be used.\n\n    app.configure(function() {\n      app.use(express.static(__dirname + '/../../public'));\n      app.use(express.cookieParser());\n      app.use(express.bodyParser());\n      app.use(express.session({ secret: 'keyboard cat' }));\n      app.use(passport.initialize());\n      app.use(passport.session());\n      app.use(app.router);\n    });\n\n#### Authenticate Requests\n\nPassport provides an `authenticate()` function, which is used as route\nmiddleware to authenticate requests.\n\n    app.post('/login', \n      passport.authenticate('local', { failureRedirect: '/login' }),\n      function(req, res) {\n        res.redirect('/');\n      });\n\n## Examples\n\nFor a complete, working example, refer to the [login example](https://github.com/jaredhanson/passport-local/tree/master/examples/login)\nincluded in [passport-local](https://github.com/jaredhanson/passport-local).\n\n## Strategies\n\nPassport has a comprehensive set of **over 120** authentication strategies\ncovering social networking, enterprise integration, API services, and more.\nThe [complete list](https://github.com/jaredhanson/passport/wiki/Strategies) is\navailable on the [wiki](https://github.com/jaredhanson/passport/wiki).\n\nThe following table lists commonly used strategies:\n\n|Strategy                                                       | Protocol                 |Developer                                       |\n|---------------------------------------------------------------|--------------------------|------------------------------------------------|\n|[Local](https://github.com/jaredhanson/passport-local)         | HTML form                |[Jared Hanson](https://github.com/jaredhanson)  |\n|[OpenID](https://github.com/jaredhanson/passport-openid)       | OpenID                   |[Jared Hanson](https://github.com/jaredhanson)  |\n|[BrowserID](https://github.com/jaredhanson/passport-browserid) | BrowserID                |[Jared Hanson](https://github.com/jaredhanson)  |\n|[Facebook](https://github.com/jaredhanson/passport-facebook)   | OAuth 2.0                |[Jared Hanson](https://github.com/jaredhanson)  |\n|[Google](https://github.com/jaredhanson/passport-google)       | OpenID                   |[Jared Hanson](https://github.com/jaredhanson)  |\n|[Google](https://github.com/jaredhanson/passport-google-oauth) | OAuth / OAuth 2.0        |[Jared Hanson](https://github.com/jaredhanson)  |\n|[Twitter](https://github.com/jaredhanson/passport-twitter)     | OAuth                    |[Jared Hanson](https://github.com/jaredhanson)  |\n\n## Related Modules\n\n- [Locomotive](https://github.com/jaredhanson/locomotive) — Powerful MVC web framework\n- [OAuthorize](https://github.com/jaredhanson/oauthorize) — OAuth service provider toolkit\n- [OAuth2orize](https://github.com/jaredhanson/oauth2orize) — OAuth 2.0 authorization server toolkit\n- [connect-ensure-login](https://github.com/jaredhanson/connect-ensure-login)  — middleware to ensure login sessions\n\nThe [modules](https://github.com/jaredhanson/passport/wiki/Modules) page on the\n[wiki](https://github.com/jaredhanson/passport/wiki) lists other useful modules\nthat build upon or integrate with Passport.\n\n## Tests\n\n    $ npm install --dev\n    $ make test\n\n[![Build Status](https://secure.travis-ci.org/jaredhanson/passport.png)](http://travis-ci.org/jaredhanson/passport)\n\n## Credits\n\n  - [Jared Hanson](http://github.com/jaredhanson)\n\n## License\n\n[The MIT License](http://opensource.org/licenses/MIT)\n\nCopyright (c) 2011-2013 Jared Hanson <[http://jaredhanson.net/](http://jaredhanson.net/)>\n",
     45  "readme": "# Passport\n\nPassport is [Express](http://expressjs.com/)-compatible authentication\nmiddleware for [Node.js](http://nodejs.org/).\n\nPassport's sole purpose is to authenticate requests, which it does through an\nextensible set of plugins known as _strategies_.  Passport does not mount\nroutes or assume any particular database schema, which maximizes flexiblity and\nallows application-level decisions to be made by the developer.  The API is\nsimple: you provide Passport a request to authenticate, and Passport provides\nhooks for controlling what occurs when authentication succeeds or fails.\n\n## Install\n\n    $ npm install passport\n\n###### Donate\n\nUsing Passport in your project?  [Donations](https://www.gittip.com/jaredhanson/)\nare greatly appreciated and help support development of this and other quality\nmodules.\n\n## Usage\n\n#### Strategies\n\nPassport uses the concept of strategies to authenticate requests.  Strategies\ncan range from verifying username and password credentials, delegated\nauthentication using [OAuth](http://oauth.net/) (for example, via [Facebook](http://www.facebook.com/)\nor [Twitter](http://twitter.com/)), or federated authentication using [OpenID](http://openid.net/).\n\nBefore authenticating requests, the strategy (or strategies) used by an\napplication must be configured.\n\n    passport.use(new LocalStrategy(\n      function(username, password, done) {\n        User.findOne({ username: username, password: password }, function (err, user) {\n          done(err, user);\n        });\n      }\n    ));\n\n#### Sessions\n\nPassport will maintain persistent login sessions.  In order for persistent\nsessions to work, the authenticated user must be serialized to the session, and\ndeserialized when subsequent requests are made.\n\nPassport does not impose any restrictions on how your user records are stored.\nInstead, you provide functions to Passport which implements the necessary\nserialization and deserialization logic.  In a typical application, this will be\nas simple as serializing the user ID, and finding the user by ID when\ndeserializing.\n\n    passport.serializeUser(function(user, done) {\n      done(null, user.id);\n    });\n\n    passport.deserializeUser(function(id, done) {\n      User.findById(id, function (err, user) {\n        done(err, user);\n      });\n    });\n\n#### Middleware\n\nTo use Passport in an [Express](http://expressjs.com/) or\n[Connect](http://senchalabs.github.com/connect/)-based application, configure it\nwith the required `passport.initialize()` middleware.  If your application uses\npersistent login sessions (recommended, but not required), `passport.session()`\nmiddleware must also be used.\n\n    app.configure(function() {\n      app.use(express.static(__dirname + '/../../public'));\n      app.use(express.cookieParser());\n      app.use(express.bodyParser());\n      app.use(express.session({ secret: 'keyboard cat' }));\n      app.use(passport.initialize());\n      app.use(passport.session());\n      app.use(app.router);\n    });\n\n#### Authenticate Requests\n\nPassport provides an `authenticate()` function, which is used as route\nmiddleware to authenticate requests.\n\n    app.post('/login', \n      passport.authenticate('local', { failureRedirect: '/login' }),\n      function(req, res) {\n        res.redirect('/');\n      });\n\n## Strategies\n\nPassport has a comprehensive set of **over 140** authentication strategies\ncovering social networking, enterprise integration, API services, and more.\nThe [complete list](https://github.com/jaredhanson/passport/wiki/Strategies) is\navailable on the [wiki](https://github.com/jaredhanson/passport/wiki).\n\nThe following table lists commonly used strategies:\n\n|Strategy                                                       | Protocol                 |Developer                                       |\n|---------------------------------------------------------------|--------------------------|------------------------------------------------|\n|[Local](https://github.com/jaredhanson/passport-local)         | HTML form                |[Jared Hanson](https://github.com/jaredhanson)  |\n|[OpenID](https://github.com/jaredhanson/passport-openid)       | OpenID                   |[Jared Hanson](https://github.com/jaredhanson)  |\n|[BrowserID](https://github.com/jaredhanson/passport-browserid) | BrowserID                |[Jared Hanson](https://github.com/jaredhanson)  |\n|[Facebook](https://github.com/jaredhanson/passport-facebook)   | OAuth 2.0                |[Jared Hanson](https://github.com/jaredhanson)  |\n|[Google](https://github.com/jaredhanson/passport-google)       | OpenID                   |[Jared Hanson](https://github.com/jaredhanson)  |\n|[Google](https://github.com/jaredhanson/passport-google-oauth) | OAuth / OAuth 2.0        |[Jared Hanson](https://github.com/jaredhanson)  |\n|[Twitter](https://github.com/jaredhanson/passport-twitter)     | OAuth                    |[Jared Hanson](https://github.com/jaredhanson)  |\n\n## Examples\n\n- For a complete, working example, refer to the [login example](https://github.com/jaredhanson/passport-local/tree/master/examples/login)\nincluded in [passport-local](https://github.com/jaredhanson/passport-local).\n- Please refer to this [tutorial](http://mherman.org/blog/2013/11/10/social-authentication-with-passport-dot-js/) on setting up various social authentication strategies, including a working example found on this [repo](https://github.com/mjhea0/passport-examples).\n\n## Related Modules\n\n- [Locomotive](https://github.com/jaredhanson/locomotive) — Powerful MVC web framework\n- [OAuthorize](https://github.com/jaredhanson/oauthorize) — OAuth service provider toolkit\n- [OAuth2orize](https://github.com/jaredhanson/oauth2orize) — OAuth 2.0 authorization server toolkit\n- [connect-ensure-login](https://github.com/jaredhanson/connect-ensure-login)  — middleware to ensure login sessions\n\nThe [modules](https://github.com/jaredhanson/passport/wiki/Modules) page on the\n[wiki](https://github.com/jaredhanson/passport/wiki) lists other useful modules\nthat build upon or integrate with Passport.\n\n## Tests\n\n    $ npm install --dev\n    $ make test\n\n[![Build Status](https://secure.travis-ci.org/jaredhanson/passport.png)](http://travis-ci.org/jaredhanson/passport)\n\n## Credits\n\n  - [Jared Hanson](http://github.com/jaredhanson)\n\n## License\n\n[The MIT License](http://opensource.org/licenses/MIT)\n\nCopyright (c) 2011-2013 Jared Hanson <[http://jaredhanson.net/](http://jaredhanson.net/)>\n",
    4646  "readmeFilename": "README.md",
    47   "_id": "passport@0.1.17",
     47  "_id": "passport@0.1.18",
    4848  "dist": {
    49     "shasum": "7743a467789ec0ed38be04e8820104cbadded67c"
     49    "shasum": "7ef09b02754a0b69704b26974f28c7e28f5e97c8"
    5050  },
    51   "_from": "passport@",
    52   "_resolved": "https://registry.npmjs.org/passport/-/passport-0.1.17.tgz"
     51  "_from": "passport@0.1.18",
     52  "_resolved": "https://registry.npmjs.org/passport/-/passport-0.1.18.tgz"
    5353}
  • Dev/trunk/src/node_modules/q/README.md

    r484 r489  
    3535
    3636```javascript
    37 Q.fcall(step1)
    38 .then(step2)
    39 .then(step3)
    40 .then(step4)
     37Q.fcall(promisedStep1)
     38.then(promisedStep2)
     39.then(promisedStep3)
     40.then(promisedStep4)
    4141.then(function (value4) {
    4242    // Do something with value4
    43 }, function (error) {
    44     // Handle any error from step1 through step4
     43})
     44.catch(function (error) {
     45    // Handle any error from all above steps
    4546})
    4647.done();
    4748```
    4849
    49 With this approach, you also get implicit error propagation,
    50 just like ``try``, ``catch``, and ``finally``.  An error in
    51 ``step1`` will flow all the way to ``step5``, where it’s
    52 caught and handled.
     50With this approach, you also get implicit error propagation, just like `try`,
     51`catch`, and `finally`.  An error in `promisedStep1` will flow all the way to
     52the `catch` function, where it’s caught and handled.  (Here `promisedStepN` is
     53a version of `stepN` that returns a promise.)
    5354
    5455The callback approach is called an “inversion of control”.
     
    7778
    7879Q can exchange promises with jQuery, Dojo, When.js, WinJS, and more.
    79 Additionally, there are many libraries that produce and consume Q promises for
    80 everything from file system/database access or RPC to templating. For a list of
    81 some of the more popular ones, see [Libraries][].
    82 
    83 Please join the Q-Continuum [mailing list](https://groups.google.com/forum/#!forum/q-continuum).
    84 
     80
     81## Resources
     82
     83Our [wiki][] contains a number of useful resources, including:
     84
     85- A method-by-method [Q API reference][reference].
     86- A growing [examples gallery][examples], showing how Q can be used to make
     87  everything better. From XHR to database access to accessing the Flickr API,
     88  Q is there for you.
     89- There are many libraries that produce and consume Q promises for everything
     90  from file system/database access or RPC to templating. For a list of some of
     91  the more popular ones, see [Libraries][].
     92- If you want materials that introduce the promise concept generally, and the
     93  below tutorial isn't doing it for you, check out our collection of
     94  [presentations, blog posts, and podcasts][resources].
     95- A guide for those [coming from jQuery's `$.Deferred`][jquery].
     96
     97We'd also love to have you join the Q-Continuum [mailing list][].
     98
     99[wiki]: https://github.com/kriskowal/q/wiki
     100[reference]: https://github.com/kriskowal/q/wiki/API-Reference
     101[examples]: https://github.com/kriskowal/q/wiki/Examples-Gallery
    85102[Libraries]: https://github.com/kriskowal/q/wiki/Libraries
     103[resources]: https://github.com/kriskowal/q/wiki/General-Promise-Resources
     104[jquery]: https://github.com/kriskowal/q/wiki/Coming-from-jQuery
     105[mailing list]: https://groups.google.com/forum/#!forum/q-continuum
    86106
    87107
     
    109129guarantee when mentally tracing the flow of your code, namely that
    110130``then`` will always return before either handler is executed.
     131
     132In this tutorial, we begin with how to consume and work with promises. We'll
     133talk about how to create them, and thus create functions like
     134`promiseMeSomething` that return promises, [below](#the-beginning).
    111135
    112136
     
    321345var funcs = [foo, bar, baz, qux];
    322346
    323 var result = Q.resolve(initialVal);
     347var result = Q(initialVal);
    324348funcs.forEach(function (f) {
    325349    result = result.then(f);
     
    333357return funcs.reduce(function (soFar, f) {
    334358    return soFar.then(f);
    335 }, Q.resolve(initialVal));
     359}, Q(initialVal));
    336360```
    337361
     
    518542    var deferred = Q.defer();
    519543    Q.when(promise, deferred.resolve);
    520     Q.when(delay(ms), function () {
     544    delay(ms).then(function () {
    521545        deferred.reject(new Error("Timed out"));
    522546    });
     
    617641
    618642```javascript
    619 return Q.when($.ajax(...))
     643return Q($.ajax(...))
    620644.then(function () {
    621645});
     
    685709
    686710If you're working with functions that make use of the Node.js callback pattern,
    687 Q provides a few useful utility functions for converting between them. The
    688 most straightforward are probably `Q.nfcall` and `Q.nfapply` ("Node function
    689 call/apply") for calling Node.js-style functions and getting back a promise:
     711where callbacks are in the form of `function(err, result)`, Q provides a few
     712useful utility functions for converting between them. The most straightforward
     713are probably `Q.nfcall` and `Q.nfapply` ("Node function call/apply") for calling
     714Node.js-style functions and getting back a promise:
    690715
    691716```javascript
     
    776801to many users, you should probably keep it off. But in development, go for it!
    777802
    778 ## Reference
    779 
    780 A method-by-method [Q API reference][reference] is available on the wiki.
    781 
    782 [reference]: https://github.com/kriskowal/q/wiki/API-Reference
    783 
    784 ## More Examples
    785 
    786 A growing [examples gallery][examples] is available on the wiki, showing how Q
    787 can be used to make everything better. From XHR to database access to accessing
    788 the Flickr API, Q is there for you.
    789 
    790 [examples]: https://github.com/kriskowal/q/wiki/Examples-Gallery
    791 
    792803## Tests
    793804
     
    796807[tests]: https://rawgithub.com/kriskowal/q/master/spec/q-spec.html
    797808
    798 ---
    799 
    800 Copyright 2009-2012 Kristopher Michael Kowal
     809## License
     810
     811Copyright 2009–2013 Kristopher Michael Kowal
    801812MIT License (enclosed)
    802813
  • Dev/trunk/src/node_modules/q/package.json

    r484 r489  
    11{
    22  "name": "q",
    3   "version": "0.9.6",
     3  "version": "0.9.7",
    44  "description": "A library for promises (CommonJS/Promises/A,B,D)",
    55  "homepage": "https://github.com/kriskowal/q",
     
    4343    "url": "http://github.com/kriskowal/q/issues"
    4444  },
    45   "licenses": [
    46     {
    47       "type": "MIT",
    48       "url": "http://github.com/kriskowal/q/raw/master/LICENSE"
    49     }
    50   ],
     45  "license": {
     46    "type": "MIT",
     47    "url": "http://github.com/kriskowal/q/raw/master/LICENSE"
     48  },
    5149  "main": "q.js",
    5250  "repository": {
     
    6058  "dependencies": {},
    6159  "devDependencies": {
    62     "jshint": "~2.1.3",
     60    "jshint": "~2.1.9",
    6361    "cover": "*",
    64     "jasmine-node": "1.2.2",
     62    "jasmine-node": "1.11.0",
    6563    "opener": "*",
    6664    "promises-aplus-tests": "1.x",
    6765    "grunt": "~0.4.1",
    6866    "grunt-cli": "~0.1.9",
    69     "grunt-contrib-uglify": "~0.2.2"
     67    "grunt-contrib-uglify": "~0.2.2",
     68    "matcha": "~0.2.0"
    7069  },
    7170  "scripts": {
    7271    "test": "jasmine-node spec && promises-aplus-tests spec/aplus-adapter",
    7372    "test-browser": "opener spec/q-spec.html",
     73    "benchmark": "matcha",
    7474    "lint": "jshint q.js",
    7575    "cover": "cover run node_modules/jasmine-node/bin/jasmine-node spec && cover report html && opener cover_html/index.html",
     
    8787    "test": "./spec"
    8888  },
    89   "readme": "[![Build Status](https://secure.travis-ci.org/kriskowal/q.png?branch=master)](http://travis-ci.org/kriskowal/q)\n\n<a href=\"http://promises-aplus.github.com/promises-spec\">\n    <img src=\"http://promises-aplus.github.com/promises-spec/assets/logo-small.png\"\n         align=\"right\" alt=\"Promises/A+ logo\" />\n</a>\n\nIf a function cannot return a value or throw an exception without\nblocking, it can return a promise instead.  A promise is an object\nthat represents the return value or the thrown exception that the\nfunction may eventually provide.  A promise can also be used as a\nproxy for a [remote object][Q-Connection] to overcome latency.\n\n[Q-Connection]: https://github.com/kriskowal/q-connection\n\nOn the first pass, promises can mitigate the “[Pyramid of\nDoom][POD]”: the situation where code marches to the right faster\nthan it marches forward.\n\n[POD]: http://calculist.org/blog/2011/12/14/why-coroutines-wont-work-on-the-web/\n\n```javascript\nstep1(function (value1) {\n    step2(value1, function(value2) {\n        step3(value2, function(value3) {\n            step4(value3, function(value4) {\n                // Do something with value4\n            });\n        });\n    });\n});\n```\n\nWith a promise library, you can flatten the pyramid.\n\n```javascript\nQ.fcall(step1)\n.then(step2)\n.then(step3)\n.then(step4)\n.then(function (value4) {\n    // Do something with value4\n}, function (error) {\n    // Handle any error from step1 through step4\n})\n.done();\n```\n\nWith this approach, you also get implicit error propagation,\njust like ``try``, ``catch``, and ``finally``.  An error in\n``step1`` will flow all the way to ``step5``, where it’s\ncaught and handled.\n\nThe callback approach is called an “inversion of control”.\nA function that accepts a callback instead of a return value\nis saying, “Don’t call me, I’ll call you.”.  Promises\n[un-invert][IOC] the inversion, cleanly separating the input\narguments from control flow arguments.  This simplifies the\nuse and creation of API’s, particularly variadic,\nrest and spread arguments.\n\n[IOC]: http://www.slideshare.net/domenicdenicola/callbacks-promises-and-coroutines-oh-my-the-evolution-of-asynchronicity-in-javascript\n\n\n## Getting Started\n\nThe Q module can be loaded as:\n\n-   A ``<script>`` tag (creating a ``Q`` global variable): ~2.5 KB minified and\n    gzipped.\n-   A Node.js and CommonJS module, available in [npm](https://npmjs.org/) as\n    the [q](https://npmjs.org/package/q) package\n-   An AMD module\n-   A [component](https://github.com/component/component) as ``microjs/q``\n-   Using [bower](http://bower.io/) as ``q``\n-   Using [NuGet](http://nuget.org/) as [Q](https://nuget.org/packages/q)\n\nQ can exchange promises with jQuery, Dojo, When.js, WinJS, and more.\nAdditionally, there are many libraries that produce and consume Q promises for\neverything from file system/database access or RPC to templating. For a list of\nsome of the more popular ones, see [Libraries][].\n\nPlease join the Q-Continuum [mailing list](https://groups.google.com/forum/#!forum/q-continuum).\n\n[Libraries]: https://github.com/kriskowal/q/wiki/Libraries\n\n\n## Tutorial\n\nPromises have a ``then`` method, which you can use to get the eventual\nreturn value (fulfillment) or thrown exception (rejection).\n\n```javascript\npromiseMeSomething()\n.then(function (value) {\n}, function (reason) {\n});\n```\n\nIf ``promiseMeSomething`` returns a promise that gets fulfilled later\nwith a return value, the first function (the fulfillment handler) will be\ncalled with the value.  However, if the ``promiseMeSomething`` function\ngets rejected later by a thrown exception, the second function (the\nrejection handler) will be called with the exception.\n\nNote that resolution of a promise is always asynchronous: that is, the\nfulfillment or rejection handler will always be called in the next turn of the\nevent loop (i.e. `process.nextTick` in Node). This gives you a nice\nguarantee when mentally tracing the flow of your code, namely that\n``then`` will always return before either handler is executed.\n\n\n### Propagation\n\nThe ``then`` method returns a promise, which in this example, I’m\nassigning to ``outputPromise``.\n\n```javascript\nvar outputPromise = getInputPromise()\n.then(function (input) {\n}, function (reason) {\n});\n```\n\nThe ``outputPromise`` variable becomes a new promise for the return\nvalue of either handler.  Since a function can only either return a\nvalue or throw an exception, only one handler will ever be called and it\nwill be responsible for resolving ``outputPromise``.\n\n-   If you return a value in a handler, ``outputPromise`` will get\n    fulfilled.\n\n-   If you throw an exception in a handler, ``outputPromise`` will get\n    rejected.\n\n-   If you return a **promise** in a handler, ``outputPromise`` will\n    “become” that promise.  Being able to become a new promise is useful\n    for managing delays, combining results, or recovering from errors.\n\nIf the ``getInputPromise()`` promise gets rejected and you omit the\nrejection handler, the **error** will go to ``outputPromise``:\n\n```javascript\nvar outputPromise = getInputPromise()\n.then(function (value) {\n});\n```\n\nIf the input promise gets fulfilled and you omit the fulfillment handler, the\n**value** will go to ``outputPromise``:\n\n```javascript\nvar outputPromise = getInputPromise()\n.then(null, function (error) {\n});\n```\n\nQ promises provide a ``fail`` shorthand for ``then`` when you are only\ninterested in handling the error:\n\n```javascript\nvar outputPromise = getInputPromise()\n.fail(function (error) {\n});\n```\n\nIf you are writing JavaScript for modern engines only or using\nCoffeeScript, you may use `catch` instead of `fail`.\n\nPromises also have a ``fin`` function that is like a ``finally`` clause.\nThe final handler gets called, with no arguments, when the promise\nreturned by ``getInputPromise()`` either returns a value or throws an\nerror.  The value returned or error thrown by ``getInputPromise()``\npasses directly to ``outputPromise`` unless the final handler fails, and\nmay be delayed if the final handler returns a promise.\n\n```javascript\nvar outputPromise = getInputPromise()\n.fin(function () {\n    // close files, database connections, stop servers, conclude tests\n});\n```\n\n-   If the handler returns a value, the value is ignored\n-   If the handler throws an error, the error passes to ``outputPromise``\n-   If the handler returns a promise, ``outputPromise`` gets postponed.  The\n    eventual value or error has the same effect as an immediate return\n    value or thrown error: a value would be ignored, an error would be\n    forwarded.\n\nIf you are writing JavaScript for modern engines only or using\nCoffeeScript, you may use `finally` instead of `fin`.\n\n### Chaining\n\nThere are two ways to chain promises.  You can chain promises either\ninside or outside handlers.  The next two examples are equivalent.\n\n```javascript\nreturn getUsername()\n.then(function (username) {\n    return getUser(username)\n    .then(function (user) {\n        // if we get here without an error,\n        // the value returned here\n        // or the exception thrown here\n        // resolves the promise returned\n        // by the first line\n    })\n});\n```\n\n```javascript\nreturn getUsername()\n.then(function (username) {\n    return getUser(username);\n})\n.then(function (user) {\n    // if we get here without an error,\n    // the value returned here\n    // or the exception thrown here\n    // resolves the promise returned\n    // by the first line\n});\n```\n\nThe only difference is nesting.  It’s useful to nest handlers if you\nneed to capture multiple input values in your closure.\n\n```javascript\nfunction authenticate() {\n    return getUsername()\n    .then(function (username) {\n        return getUser(username);\n    })\n    // chained because we will not need the user name in the next event\n    .then(function (user) {\n        return getPassword()\n        // nested because we need both user and password next\n        .then(function (password) {\n            if (user.passwordHash !== hash(password)) {\n                throw new Error(\"Can't authenticate\");\n            }\n        });\n    });\n}\n```\n\n\n### Combination\n\nYou can turn an array of promises into a promise for the whole,\nfulfilled array using ``all``.\n\n```javascript\nreturn Q.all([\n    eventualAdd(2, 2),\n    eventualAdd(10, 20)\n]);\n```\n\nIf you have a promise for an array, you can use ``spread`` as a\nreplacement for ``then``.  The ``spread`` function “spreads” the\nvalues over the arguments of the fulfillment handler.  The rejection handler\nwill get called at the first sign of failure.  That is, whichever of\nthe recived promises fails first gets handled by the rejection handler.\n\n```javascript\nfunction eventualAdd(a, b) {\n    return Q.spread([a, b], function (a, b) {\n        return a + b;\n    })\n}\n```\n\nBut ``spread`` calls ``all`` initially, so you can skip it in chains.\n\n```javascript\nreturn getUsername()\n.then(function (username) {\n    return [username, getUser(username)];\n})\n.spread(function (username, user) {\n});\n```\n\nThe ``all`` function returns a promise for an array of values.  When this\npromise is fulfilled, the array contains the fulfillment values of the original\npromises, in the same order as those promises.  If one of the given promises\nis rejected, the returned promise is immediately rejected, not waiting for the\nrest of the batch.  If you want to wait for all of the promises to either be\nfulfilled or rejected, you can use ``allSettled``.\n\n```javascript\nQ.allSettled(promises)\n.then(function (results) {\n    results.forEach(function (result) {\n        if (result.state === \"fulfilled\") {\n            var value = result.value;\n        } else {\n            var reason = result.reason;\n        }\n    });\n});\n```\n\n\n### Sequences\n\nIf you have a number of promise-producing functions that need\nto be run sequentially, you can of course do so manually:\n\n```javascript\nreturn foo(initialVal).then(bar).then(baz).then(qux);\n```\n\nHowever, if you want to run a dynamically constructed sequence of\nfunctions, you'll want something like this:\n\n```javascript\nvar funcs = [foo, bar, baz, qux];\n\nvar result = Q.resolve(initialVal);\nfuncs.forEach(function (f) {\n    result = result.then(f);\n});\nreturn result;\n```\n\nYou can make this slightly more compact using `reduce`:\n\n```javascript\nreturn funcs.reduce(function (soFar, f) {\n    return soFar.then(f);\n}, Q.resolve(initialVal));\n```\n\nOr, you could use th ultra-compact version:\n\n```javascript\nreturn funcs.reduce(Q.when, Q());\n```\n\n### Handling Errors\n\nOne sometimes-unintuive aspect of promises is that if you throw an\nexception in the fulfillment handler, it will not be be caught by the error\nhandler.\n\n```javascript\nreturn foo()\n.then(function (value) {\n    throw new Error(\"Can't bar.\");\n}, function (error) {\n    // We only get here if \"foo\" fails\n});\n```\n\nTo see why this is, consider the parallel between promises and\n``try``/``catch``. We are ``try``-ing to execute ``foo()``: the error\nhandler represents a ``catch`` for ``foo()``, while the fulfillment handler\nrepresents code that happens *after* the ``try``/``catch`` block.\nThat code then needs its own ``try``/``catch`` block.\n\nIn terms of promises, this means chaining your rejection handler:\n\n```javascript\nreturn foo()\n.then(function (value) {\n    throw new Error(\"Can't bar.\");\n})\n.fail(function (error) {\n    // We get here with either foo's error or bar's error\n});\n```\n\n### Progress Notification\n\nIt's possible for promises to report their progress, e.g. for tasks that take a\nlong time like a file upload. Not all promises will implement progress\nnotifications, but for those that do, you can consume the progress values using\na third parameter to ``then``:\n\n```javascript\nreturn uploadFile()\n.then(function () {\n    // Success uploading the file\n}, function (err) {\n    // There was an error, and we get the reason for error\n}, function (progress) {\n    // We get notified of the upload's progress as it is executed\n});\n```\n\nLike `fail`, Q also provides a shorthand for progress callbacks\ncalled `progress`:\n\n```javascript\nreturn uploadFile().progress(function (progress) {\n    // We get notified of the upload's progress\n});\n```\n\n### The End\n\nWhen you get to the end of a chain of promises, you should either\nreturn the last promise or end the chain.  Since handlers catch\nerrors, it’s an unfortunate pattern that the exceptions can go\nunobserved.\n\nSo, either return it,\n\n```javascript\nreturn foo()\n.then(function () {\n    return \"bar\";\n});\n```\n\nOr, end it.\n\n```javascript\nfoo()\n.then(function () {\n    return \"bar\";\n})\n.done();\n```\n\nEnding a promise chain makes sure that, if an error doesn’t get\nhandled before the end, it will get rethrown and reported.\n\nThis is a stopgap. We are exploring ways to make unhandled errors\nvisible without any explicit handling.\n\n\n### The Beginning\n\nEverything above assumes you get a promise from somewhere else.  This\nis the common case.  Every once in a while, you will need to create a\npromise from scratch.\n\n#### Using ``Q.fcall``\n\nYou can create a promise from a value using ``Q.fcall``.  This returns a\npromise for 10.\n\n```javascript\nreturn Q.fcall(function () {\n    return 10;\n});\n```\n\nYou can also use ``fcall`` to get a promise for an exception.\n\n```javascript\nreturn Q.fcall(function () {\n    throw new Error(\"Can't do it\");\n});\n```\n\nAs the name implies, ``fcall`` can call functions, or even promised\nfunctions.  This uses the ``eventualAdd`` function above to add two\nnumbers.\n\n```javascript\nreturn Q.fcall(eventualAdd, 2, 2);\n```\n\n\n#### Using Deferreds\n\nIf you have to interface with asynchronous functions that are callback-based\ninstead of promise-based, Q provides a few shortcuts (like ``Q.nfcall`` and\nfriends). But much of the time, the solution will be to use *deferreds*.\n\n```javascript\nvar deferred = Q.defer();\nFS.readFile(\"foo.txt\", \"utf-8\", function (error, text) {\n    if (error) {\n        deferred.reject(new Error(error));\n    } else {\n        deferred.resolve(text);\n    }\n});\nreturn deferred.promise;\n```\n\nNote that a deferred can be resolved with a value or a promise.  The\n``reject`` function is a shorthand for resolving with a rejected\npromise.\n\n```javascript\n// this:\ndeferred.reject(new Error(\"Can't do it\"));\n\n// is shorthand for:\nvar rejection = Q.fcall(function () {\n    throw new Error(\"Can't do it\");\n});\ndeferred.resolve(rejection);\n```\n\nThis is a simplified implementation of ``Q.delay``.\n\n```javascript\nfunction delay(ms) {\n    var deferred = Q.defer();\n    setTimeout(deferred.resolve, ms);\n    return deferred.promise;\n}\n```\n\nThis is a simplified implementation of ``Q.timeout``\n\n```javascript\nfunction timeout(promise, ms) {\n    var deferred = Q.defer();\n    Q.when(promise, deferred.resolve);\n    Q.when(delay(ms), function () {\n        deferred.reject(new Error(\"Timed out\"));\n    });\n    return deferred.promise;\n}\n```\n\nFinally, you can send a progress notification to the promise with\n``deferred.notify``.\n\nFor illustration, this is a wrapper for XML HTTP requests in the browser. Note\nthat a more [thorough][XHR] implementation would be in order in practice.\n\n[XHR]: https://github.com/montagejs/mr/blob/71e8df99bb4f0584985accd6f2801ef3015b9763/browser.js#L29-L73\n\n```javascript\nfunction requestOkText(url) {\n    var request = new XMLHttpRequest();\n    var deferred = Q.defer();\n\n    request.open(\"GET\", url, true);\n    request.onload = onload;\n    request.onerror = onerror;\n    request.onprogress = onprogress;\n    request.send();\n\n    function onload() {\n        if (request.status === 200) {\n            deferred.resolve(request.responseText);\n        } else {\n            deferred.reject(new Error(\"Status code was \" + request.status));\n        }\n    }\n\n    function onerror() {\n        deferred.reject(new Error(\"Can't XHR \" + JSON.stringify(url)));\n    }\n\n    function onprogress(event) {\n        deferred.notify(event.loaded / event.total);\n    }\n\n    return deferred.promise;\n}\n```\n\nBelow is an example of how to use this ``requestOkText`` function:\n\n```javascript\nrequestOkText(\"http://localhost:3000\")\n.then(function (responseText) {\n    // If the HTTP response returns 200 OK, log the response text.\n    console.log(responseText);\n}, function (error) {\n    // If there's an error or a non-200 status code, log the error.\n    console.error(error);\n}, function (progress) {\n    // Log the progress as it comes in.\n    console.log(\"Request progress: \" + Math.round(progress * 100) + \"%\");\n});\n```\n\n### The Middle\n\nIf you are using a function that may return a promise, but just might\nreturn a value if it doesn’t need to defer, you can use the “static”\nmethods of the Q library.\n\nThe ``when`` function is the static equivalent for ``then``.\n\n```javascript\nreturn Q.when(valueOrPromise, function (value) {\n}, function (error) {\n});\n```\n\nAll of the other methods on a promise have static analogs with the\nsame name.\n\nThe following are equivalent:\n\n```javascript\nreturn Q.all([a, b]);\n```\n\n```javascript\nreturn Q.fcall(function () {\n    return [a, b];\n})\n.all();\n```\n\nWhen working with promises provided by other libraries, you should\nconvert it to a Q promise.  Not all promise libraries make the same\nguarantees as Q and certainly don’t provide all of the same methods.\nMost libraries only provide a partially functional ``then`` method.\nThis thankfully is all we need to turn them into vibrant Q promises.\n\n```javascript\nreturn Q.when($.ajax(...))\n.then(function () {\n});\n```\n\nIf there is any chance that the promise you receive is not a Q promise\nas provided by your library, you should wrap it using a Q function.\nYou can even use ``Q.invoke`` as a shorthand.\n\n```javascript\nreturn Q.invoke($, 'ajax', ...)\n.then(function () {\n});\n```\n\n\n### Over the Wire\n\nA promise can serve as a proxy for another object, even a remote\nobject.  There are methods that allow you to optimistically manipulate\nproperties or call functions.  All of these interactions return\npromises, so they can be chained.\n\n```\ndirect manipulation         using a promise as a proxy\n--------------------------  -------------------------------\nvalue.foo                   promise.get(\"foo\")\nvalue.foo = value           promise.put(\"foo\", value)\ndelete value.foo            promise.del(\"foo\")\nvalue.foo(...args)          promise.post(\"foo\", [args])\nvalue.foo(...args)          promise.invoke(\"foo\", ...args)\nvalue(...args)              promise.fapply([args])\nvalue(...args)              promise.fcall(...args)\n```\n\nIf the promise is a proxy for a remote object, you can shave\nround-trips by using these functions instead of ``then``.  To take\nadvantage of promises for remote objects, check out [Q-Connection][].\n\n[Q-Connection]: https://github.com/kriskowal/q-connection\n\nEven in the case of non-remote objects, these methods can be used as\nshorthand for particularly-simple fulfillment handlers. For example, you\ncan replace\n\n```javascript\nreturn Q.fcall(function () {\n    return [{ foo: \"bar\" }, { foo: \"baz\" }];\n})\n.then(function (value) {\n    return value[0].foo;\n});\n```\n\nwith\n\n```javascript\nreturn Q.fcall(function () {\n    return [{ foo: \"bar\" }, { foo: \"baz\" }];\n})\n.get(0)\n.get(\"foo\");\n```\n\n\n### Adapting Node\n\nIf you're working with functions that make use of the Node.js callback pattern,\nQ provides a few useful utility functions for converting between them. The\nmost straightforward are probably `Q.nfcall` and `Q.nfapply` (\"Node function\ncall/apply\") for calling Node.js-style functions and getting back a promise:\n\n```javascript\nreturn Q.nfcall(FS.readFile, \"foo.txt\", \"utf-8\");\nreturn Q.nfapply(FS.readFile, [\"foo.txt\", \"utf-8\"]);\n```\n\nIf you are working with methods, instead of simple functions, you can easily\nrun in to the usual problems where passing a method to another function—like\n`Q.nfcall`—\"un-binds\" the method from its owner. To avoid this, you can either\nuse `Function.prototype.bind` or some nice shortcut methods we provide:\n\n```javascript\nreturn Q.ninvoke(redisClient, \"get\", \"user:1:id\");\nreturn Q.npost(redisClient, \"get\", [\"user:1:id\"]);\n```\n\nYou can also create reusable wrappers with `Q.denodeify` or `Q.nbind`:\n\n```javascript\nvar readFile = Q.denodeify(FS.readFile);\nreturn readFile(\"foo.txt\", \"utf-8\");\n\nvar redisClientGet = Q.nbind(redisClient.get, redisClient);\nreturn redisClientGet(\"user:1:id\");\n```\n\nFinally, if you're working with raw deferred objects, there is a\n`makeNodeResolver` method on deferreds that can be handy:\n\n```javascript\nvar deferred = Q.defer();\nFS.readFile(\"foo.txt\", \"utf-8\", deferred.makeNodeResolver());\nreturn deferred.promise;\n```\n\n### Long Stack Traces\n\nQ comes with optional support for “long stack traces,” wherein the `stack`\nproperty of `Error` rejection reasons is rewritten to be traced along\nasynchronous jumps instead of stopping at the most recent one. As an example:\n\n```js\nfunction theDepthsOfMyProgram() {\n  Q.delay(100).done(function explode() {\n    throw new Error(\"boo!\");\n  });\n}\n\ntheDepthsOfMyProgram();\n```\n\nusually would give a rather unhelpful stack trace looking something like\n\n```\nError: boo!\n    at explode (/path/to/test.js:3:11)\n    at _fulfilled (/path/to/test.js:q:54)\n    at resolvedValue.promiseDispatch.done (/path/to/q.js:823:30)\n    at makePromise.promise.promiseDispatch (/path/to/q.js:496:13)\n    at pending (/path/to/q.js:397:39)\n    at process.startup.processNextTick.process._tickCallback (node.js:244:9)\n```\n\nBut, if you turn this feature on by setting\n\n```js\nQ.longStackSupport = true;\n```\n\nthen the above code gives a nice stack trace to the tune of\n\n```\nError: boo!\n    at explode (/path/to/test.js:3:11)\nFrom previous event:\n    at theDepthsOfMyProgram (/path/to/test.js:2:16)\n    at Object.<anonymous> (/path/to/test.js:7:1)\n```\n\nNote how you can see the the function that triggered the async operation in the\nstack trace! This is very helpful for debugging, as otherwise you end up getting\nonly the first line, plus a bunch of Q internals, with no sign of where the\noperation started.\n\nThis feature does come with somewhat-serious performance and memory overhead,\nhowever. If you're working with lots of promises, or trying to scale a server\nto many users, you should probably keep it off. But in development, go for it!\n\n## Reference\n\nA method-by-method [Q API reference][reference] is available on the wiki.\n\n[reference]: https://github.com/kriskowal/q/wiki/API-Reference\n\n## More Examples\n\nA growing [examples gallery][examples] is available on the wiki, showing how Q\ncan be used to make everything better. From XHR to database access to accessing\nthe Flickr API, Q is there for you.\n\n[examples]: https://github.com/kriskowal/q/wiki/Examples-Gallery\n\n## Tests\n\nYou can view the results of the Q test suite [in your browser][tests]!\n\n[tests]: https://rawgithub.com/kriskowal/q/master/spec/q-spec.html\n\n---\n\nCopyright 2009-2012 Kristopher Michael Kowal\nMIT License (enclosed)\n\n",
     89  "readme": "[![Build Status](https://secure.travis-ci.org/kriskowal/q.png?branch=master)](http://travis-ci.org/kriskowal/q)\n\n<a href=\"http://promises-aplus.github.com/promises-spec\">\n    <img src=\"http://promises-aplus.github.com/promises-spec/assets/logo-small.png\"\n         align=\"right\" alt=\"Promises/A+ logo\" />\n</a>\n\nIf a function cannot return a value or throw an exception without\nblocking, it can return a promise instead.  A promise is an object\nthat represents the return value or the thrown exception that the\nfunction may eventually provide.  A promise can also be used as a\nproxy for a [remote object][Q-Connection] to overcome latency.\n\n[Q-Connection]: https://github.com/kriskowal/q-connection\n\nOn the first pass, promises can mitigate the “[Pyramid of\nDoom][POD]”: the situation where code marches to the right faster\nthan it marches forward.\n\n[POD]: http://calculist.org/blog/2011/12/14/why-coroutines-wont-work-on-the-web/\n\n```javascript\nstep1(function (value1) {\n    step2(value1, function(value2) {\n        step3(value2, function(value3) {\n            step4(value3, function(value4) {\n                // Do something with value4\n            });\n        });\n    });\n});\n```\n\nWith a promise library, you can flatten the pyramid.\n\n```javascript\nQ.fcall(promisedStep1)\n.then(promisedStep2)\n.then(promisedStep3)\n.then(promisedStep4)\n.then(function (value4) {\n    // Do something with value4\n})\n.catch(function (error) {\n    // Handle any error from all above steps\n})\n.done();\n```\n\nWith this approach, you also get implicit error propagation, just like `try`,\n`catch`, and `finally`.  An error in `promisedStep1` will flow all the way to\nthe `catch` function, where it’s caught and handled.  (Here `promisedStepN` is\na version of `stepN` that returns a promise.)\n\nThe callback approach is called an “inversion of control”.\nA function that accepts a callback instead of a return value\nis saying, “Don’t call me, I’ll call you.”.  Promises\n[un-invert][IOC] the inversion, cleanly separating the input\narguments from control flow arguments.  This simplifies the\nuse and creation of API’s, particularly variadic,\nrest and spread arguments.\n\n[IOC]: http://www.slideshare.net/domenicdenicola/callbacks-promises-and-coroutines-oh-my-the-evolution-of-asynchronicity-in-javascript\n\n\n## Getting Started\n\nThe Q module can be loaded as:\n\n-   A ``<script>`` tag (creating a ``Q`` global variable): ~2.5 KB minified and\n    gzipped.\n-   A Node.js and CommonJS module, available in [npm](https://npmjs.org/) as\n    the [q](https://npmjs.org/package/q) package\n-   An AMD module\n-   A [component](https://github.com/component/component) as ``microjs/q``\n-   Using [bower](http://bower.io/) as ``q``\n-   Using [NuGet](http://nuget.org/) as [Q](https://nuget.org/packages/q)\n\nQ can exchange promises with jQuery, Dojo, When.js, WinJS, and more.\n\n## Resources\n\nOur [wiki][] contains a number of useful resources, including:\n\n- A method-by-method [Q API reference][reference].\n- A growing [examples gallery][examples], showing how Q can be used to make\n  everything better. From XHR to database access to accessing the Flickr API,\n  Q is there for you.\n- There are many libraries that produce and consume Q promises for everything\n  from file system/database access or RPC to templating. For a list of some of\n  the more popular ones, see [Libraries][].\n- If you want materials that introduce the promise concept generally, and the\n  below tutorial isn't doing it for you, check out our collection of\n  [presentations, blog posts, and podcasts][resources].\n- A guide for those [coming from jQuery's `$.Deferred`][jquery].\n\nWe'd also love to have you join the Q-Continuum [mailing list][].\n\n[wiki]: https://github.com/kriskowal/q/wiki\n[reference]: https://github.com/kriskowal/q/wiki/API-Reference\n[examples]: https://github.com/kriskowal/q/wiki/Examples-Gallery\n[Libraries]: https://github.com/kriskowal/q/wiki/Libraries\n[resources]: https://github.com/kriskowal/q/wiki/General-Promise-Resources\n[jquery]: https://github.com/kriskowal/q/wiki/Coming-from-jQuery\n[mailing list]: https://groups.google.com/forum/#!forum/q-continuum\n\n\n## Tutorial\n\nPromises have a ``then`` method, which you can use to get the eventual\nreturn value (fulfillment) or thrown exception (rejection).\n\n```javascript\npromiseMeSomething()\n.then(function (value) {\n}, function (reason) {\n});\n```\n\nIf ``promiseMeSomething`` returns a promise that gets fulfilled later\nwith a return value, the first function (the fulfillment handler) will be\ncalled with the value.  However, if the ``promiseMeSomething`` function\ngets rejected later by a thrown exception, the second function (the\nrejection handler) will be called with the exception.\n\nNote that resolution of a promise is always asynchronous: that is, the\nfulfillment or rejection handler will always be called in the next turn of the\nevent loop (i.e. `process.nextTick` in Node). This gives you a nice\nguarantee when mentally tracing the flow of your code, namely that\n``then`` will always return before either handler is executed.\n\nIn this tutorial, we begin with how to consume and work with promises. We'll\ntalk about how to create them, and thus create functions like\n`promiseMeSomething` that return promises, [below](#the-beginning).\n\n\n### Propagation\n\nThe ``then`` method returns a promise, which in this example, I’m\nassigning to ``outputPromise``.\n\n```javascript\nvar outputPromise = getInputPromise()\n.then(function (input) {\n}, function (reason) {\n});\n```\n\nThe ``outputPromise`` variable becomes a new promise for the return\nvalue of either handler.  Since a function can only either return a\nvalue or throw an exception, only one handler will ever be called and it\nwill be responsible for resolving ``outputPromise``.\n\n-   If you return a value in a handler, ``outputPromise`` will get\n    fulfilled.\n\n-   If you throw an exception in a handler, ``outputPromise`` will get\n    rejected.\n\n-   If you return a **promise** in a handler, ``outputPromise`` will\n    “become” that promise.  Being able to become a new promise is useful\n    for managing delays, combining results, or recovering from errors.\n\nIf the ``getInputPromise()`` promise gets rejected and you omit the\nrejection handler, the **error** will go to ``outputPromise``:\n\n```javascript\nvar outputPromise = getInputPromise()\n.then(function (value) {\n});\n```\n\nIf the input promise gets fulfilled and you omit the fulfillment handler, the\n**value** will go to ``outputPromise``:\n\n```javascript\nvar outputPromise = getInputPromise()\n.then(null, function (error) {\n});\n```\n\nQ promises provide a ``fail`` shorthand for ``then`` when you are only\ninterested in handling the error:\n\n```javascript\nvar outputPromise = getInputPromise()\n.fail(function (error) {\n});\n```\n\nIf you are writing JavaScript for modern engines only or using\nCoffeeScript, you may use `catch` instead of `fail`.\n\nPromises also have a ``fin`` function that is like a ``finally`` clause.\nThe final handler gets called, with no arguments, when the promise\nreturned by ``getInputPromise()`` either returns a value or throws an\nerror.  The value returned or error thrown by ``getInputPromise()``\npasses directly to ``outputPromise`` unless the final handler fails, and\nmay be delayed if the final handler returns a promise.\n\n```javascript\nvar outputPromise = getInputPromise()\n.fin(function () {\n    // close files, database connections, stop servers, conclude tests\n});\n```\n\n-   If the handler returns a value, the value is ignored\n-   If the handler throws an error, the error passes to ``outputPromise``\n-   If the handler returns a promise, ``outputPromise`` gets postponed.  The\n    eventual value or error has the same effect as an immediate return\n    value or thrown error: a value would be ignored, an error would be\n    forwarded.\n\nIf you are writing JavaScript for modern engines only or using\nCoffeeScript, you may use `finally` instead of `fin`.\n\n### Chaining\n\nThere are two ways to chain promises.  You can chain promises either\ninside or outside handlers.  The next two examples are equivalent.\n\n```javascript\nreturn getUsername()\n.then(function (username) {\n    return getUser(username)\n    .then(function (user) {\n        // if we get here without an error,\n        // the value returned here\n        // or the exception thrown here\n        // resolves the promise returned\n        // by the first line\n    })\n});\n```\n\n```javascript\nreturn getUsername()\n.then(function (username) {\n    return getUser(username);\n})\n.then(function (user) {\n    // if we get here without an error,\n    // the value returned here\n    // or the exception thrown here\n    // resolves the promise returned\n    // by the first line\n});\n```\n\nThe only difference is nesting.  It’s useful to nest handlers if you\nneed to capture multiple input values in your closure.\n\n```javascript\nfunction authenticate() {\n    return getUsername()\n    .then(function (username) {\n        return getUser(username);\n    })\n    // chained because we will not need the user name in the next event\n    .then(function (user) {\n        return getPassword()\n        // nested because we need both user and password next\n        .then(function (password) {\n            if (user.passwordHash !== hash(password)) {\n                throw new Error(\"Can't authenticate\");\n            }\n        });\n    });\n}\n```\n\n\n### Combination\n\nYou can turn an array of promises into a promise for the whole,\nfulfilled array using ``all``.\n\n```javascript\nreturn Q.all([\n    eventualAdd(2, 2),\n    eventualAdd(10, 20)\n]);\n```\n\nIf you have a promise for an array, you can use ``spread`` as a\nreplacement for ``then``.  The ``spread`` function “spreads” the\nvalues over the arguments of the fulfillment handler.  The rejection handler\nwill get called at the first sign of failure.  That is, whichever of\nthe recived promises fails first gets handled by the rejection handler.\n\n```javascript\nfunction eventualAdd(a, b) {\n    return Q.spread([a, b], function (a, b) {\n        return a + b;\n    })\n}\n```\n\nBut ``spread`` calls ``all`` initially, so you can skip it in chains.\n\n```javascript\nreturn getUsername()\n.then(function (username) {\n    return [username, getUser(username)];\n})\n.spread(function (username, user) {\n});\n```\n\nThe ``all`` function returns a promise for an array of values.  When this\npromise is fulfilled, the array contains the fulfillment values of the original\npromises, in the same order as those promises.  If one of the given promises\nis rejected, the returned promise is immediately rejected, not waiting for the\nrest of the batch.  If you want to wait for all of the promises to either be\nfulfilled or rejected, you can use ``allSettled``.\n\n```javascript\nQ.allSettled(promises)\n.then(function (results) {\n    results.forEach(function (result) {\n        if (result.state === \"fulfilled\") {\n            var value = result.value;\n        } else {\n            var reason = result.reason;\n        }\n    });\n});\n```\n\n\n### Sequences\n\nIf you have a number of promise-producing functions that need\nto be run sequentially, you can of course do so manually:\n\n```javascript\nreturn foo(initialVal).then(bar).then(baz).then(qux);\n```\n\nHowever, if you want to run a dynamically constructed sequence of\nfunctions, you'll want something like this:\n\n```javascript\nvar funcs = [foo, bar, baz, qux];\n\nvar result = Q(initialVal);\nfuncs.forEach(function (f) {\n    result = result.then(f);\n});\nreturn result;\n```\n\nYou can make this slightly more compact using `reduce`:\n\n```javascript\nreturn funcs.reduce(function (soFar, f) {\n    return soFar.then(f);\n}, Q(initialVal));\n```\n\nOr, you could use th ultra-compact version:\n\n```javascript\nreturn funcs.reduce(Q.when, Q());\n```\n\n### Handling Errors\n\nOne sometimes-unintuive aspect of promises is that if you throw an\nexception in the fulfillment handler, it will not be be caught by the error\nhandler.\n\n```javascript\nreturn foo()\n.then(function (value) {\n    throw new Error(\"Can't bar.\");\n}, function (error) {\n    // We only get here if \"foo\" fails\n});\n```\n\nTo see why this is, consider the parallel between promises and\n``try``/``catch``. We are ``try``-ing to execute ``foo()``: the error\nhandler represents a ``catch`` for ``foo()``, while the fulfillment handler\nrepresents code that happens *after* the ``try``/``catch`` block.\nThat code then needs its own ``try``/``catch`` block.\n\nIn terms of promises, this means chaining your rejection handler:\n\n```javascript\nreturn foo()\n.then(function (value) {\n    throw new Error(\"Can't bar.\");\n})\n.fail(function (error) {\n    // We get here with either foo's error or bar's error\n});\n```\n\n### Progress Notification\n\nIt's possible for promises to report their progress, e.g. for tasks that take a\nlong time like a file upload. Not all promises will implement progress\nnotifications, but for those that do, you can consume the progress values using\na third parameter to ``then``:\n\n```javascript\nreturn uploadFile()\n.then(function () {\n    // Success uploading the file\n}, function (err) {\n    // There was an error, and we get the reason for error\n}, function (progress) {\n    // We get notified of the upload's progress as it is executed\n});\n```\n\nLike `fail`, Q also provides a shorthand for progress callbacks\ncalled `progress`:\n\n```javascript\nreturn uploadFile().progress(function (progress) {\n    // We get notified of the upload's progress\n});\n```\n\n### The End\n\nWhen you get to the end of a chain of promises, you should either\nreturn the last promise or end the chain.  Since handlers catch\nerrors, it’s an unfortunate pattern that the exceptions can go\nunobserved.\n\nSo, either return it,\n\n```javascript\nreturn foo()\n.then(function () {\n    return \"bar\";\n});\n```\n\nOr, end it.\n\n```javascript\nfoo()\n.then(function () {\n    return \"bar\";\n})\n.done();\n```\n\nEnding a promise chain makes sure that, if an error doesn’t get\nhandled before the end, it will get rethrown and reported.\n\nThis is a stopgap. We are exploring ways to make unhandled errors\nvisible without any explicit handling.\n\n\n### The Beginning\n\nEverything above assumes you get a promise from somewhere else.  This\nis the common case.  Every once in a while, you will need to create a\npromise from scratch.\n\n#### Using ``Q.fcall``\n\nYou can create a promise from a value using ``Q.fcall``.  This returns a\npromise for 10.\n\n```javascript\nreturn Q.fcall(function () {\n    return 10;\n});\n```\n\nYou can also use ``fcall`` to get a promise for an exception.\n\n```javascript\nreturn Q.fcall(function () {\n    throw new Error(\"Can't do it\");\n});\n```\n\nAs the name implies, ``fcall`` can call functions, or even promised\nfunctions.  This uses the ``eventualAdd`` function above to add two\nnumbers.\n\n```javascript\nreturn Q.fcall(eventualAdd, 2, 2);\n```\n\n\n#### Using Deferreds\n\nIf you have to interface with asynchronous functions that are callback-based\ninstead of promise-based, Q provides a few shortcuts (like ``Q.nfcall`` and\nfriends). But much of the time, the solution will be to use *deferreds*.\n\n```javascript\nvar deferred = Q.defer();\nFS.readFile(\"foo.txt\", \"utf-8\", function (error, text) {\n    if (error) {\n        deferred.reject(new Error(error));\n    } else {\n        deferred.resolve(text);\n    }\n});\nreturn deferred.promise;\n```\n\nNote that a deferred can be resolved with a value or a promise.  The\n``reject`` function is a shorthand for resolving with a rejected\npromise.\n\n```javascript\n// this:\ndeferred.reject(new Error(\"Can't do it\"));\n\n// is shorthand for:\nvar rejection = Q.fcall(function () {\n    throw new Error(\"Can't do it\");\n});\ndeferred.resolve(rejection);\n```\n\nThis is a simplified implementation of ``Q.delay``.\n\n```javascript\nfunction delay(ms) {\n    var deferred = Q.defer();\n    setTimeout(deferred.resolve, ms);\n    return deferred.promise;\n}\n```\n\nThis is a simplified implementation of ``Q.timeout``\n\n```javascript\nfunction timeout(promise, ms) {\n    var deferred = Q.defer();\n    Q.when(promise, deferred.resolve);\n    delay(ms).then(function () {\n        deferred.reject(new Error(\"Timed out\"));\n    });\n    return deferred.promise;\n}\n```\n\nFinally, you can send a progress notification to the promise with\n``deferred.notify``.\n\nFor illustration, this is a wrapper for XML HTTP requests in the browser. Note\nthat a more [thorough][XHR] implementation would be in order in practice.\n\n[XHR]: https://github.com/montagejs/mr/blob/71e8df99bb4f0584985accd6f2801ef3015b9763/browser.js#L29-L73\n\n```javascript\nfunction requestOkText(url) {\n    var request = new XMLHttpRequest();\n    var deferred = Q.defer();\n\n    request.open(\"GET\", url, true);\n    request.onload = onload;\n    request.onerror = onerror;\n    request.onprogress = onprogress;\n    request.send();\n\n    function onload() {\n        if (request.status === 200) {\n            deferred.resolve(request.responseText);\n        } else {\n            deferred.reject(new Error(\"Status code was \" + request.status));\n        }\n    }\n\n    function onerror() {\n        deferred.reject(new Error(\"Can't XHR \" + JSON.stringify(url)));\n    }\n\n    function onprogress(event) {\n        deferred.notify(event.loaded / event.total);\n    }\n\n    return deferred.promise;\n}\n```\n\nBelow is an example of how to use this ``requestOkText`` function:\n\n```javascript\nrequestOkText(\"http://localhost:3000\")\n.then(function (responseText) {\n    // If the HTTP response returns 200 OK, log the response text.\n    console.log(responseText);\n}, function (error) {\n    // If there's an error or a non-200 status code, log the error.\n    console.error(error);\n}, function (progress) {\n    // Log the progress as it comes in.\n    console.log(\"Request progress: \" + Math.round(progress * 100) + \"%\");\n});\n```\n\n### The Middle\n\nIf you are using a function that may return a promise, but just might\nreturn a value if it doesn’t need to defer, you can use the “static”\nmethods of the Q library.\n\nThe ``when`` function is the static equivalent for ``then``.\n\n```javascript\nreturn Q.when(valueOrPromise, function (value) {\n}, function (error) {\n});\n```\n\nAll of the other methods on a promise have static analogs with the\nsame name.\n\nThe following are equivalent:\n\n```javascript\nreturn Q.all([a, b]);\n```\n\n```javascript\nreturn Q.fcall(function () {\n    return [a, b];\n})\n.all();\n```\n\nWhen working with promises provided by other libraries, you should\nconvert it to a Q promise.  Not all promise libraries make the same\nguarantees as Q and certainly don’t provide all of the same methods.\nMost libraries only provide a partially functional ``then`` method.\nThis thankfully is all we need to turn them into vibrant Q promises.\n\n```javascript\nreturn Q($.ajax(...))\n.then(function () {\n});\n```\n\nIf there is any chance that the promise you receive is not a Q promise\nas provided by your library, you should wrap it using a Q function.\nYou can even use ``Q.invoke`` as a shorthand.\n\n```javascript\nreturn Q.invoke($, 'ajax', ...)\n.then(function () {\n});\n```\n\n\n### Over the Wire\n\nA promise can serve as a proxy for another object, even a remote\nobject.  There are methods that allow you to optimistically manipulate\nproperties or call functions.  All of these interactions return\npromises, so they can be chained.\n\n```\ndirect manipulation         using a promise as a proxy\n--------------------------  -------------------------------\nvalue.foo                   promise.get(\"foo\")\nvalue.foo = value           promise.put(\"foo\", value)\ndelete value.foo            promise.del(\"foo\")\nvalue.foo(...args)          promise.post(\"foo\", [args])\nvalue.foo(...args)          promise.invoke(\"foo\", ...args)\nvalue(...args)              promise.fapply([args])\nvalue(...args)              promise.fcall(...args)\n```\n\nIf the promise is a proxy for a remote object, you can shave\nround-trips by using these functions instead of ``then``.  To take\nadvantage of promises for remote objects, check out [Q-Connection][].\n\n[Q-Connection]: https://github.com/kriskowal/q-connection\n\nEven in the case of non-remote objects, these methods can be used as\nshorthand for particularly-simple fulfillment handlers. For example, you\ncan replace\n\n```javascript\nreturn Q.fcall(function () {\n    return [{ foo: \"bar\" }, { foo: \"baz\" }];\n})\n.then(function (value) {\n    return value[0].foo;\n});\n```\n\nwith\n\n```javascript\nreturn Q.fcall(function () {\n    return [{ foo: \"bar\" }, { foo: \"baz\" }];\n})\n.get(0)\n.get(\"foo\");\n```\n\n\n### Adapting Node\n\nIf you're working with functions that make use of the Node.js callback pattern,\nwhere callbacks are in the form of `function(err, result)`, Q provides a few\nuseful utility functions for converting between them. The most straightforward\nare probably `Q.nfcall` and `Q.nfapply` (\"Node function call/apply\") for calling\nNode.js-style functions and getting back a promise:\n\n```javascript\nreturn Q.nfcall(FS.readFile, \"foo.txt\", \"utf-8\");\nreturn Q.nfapply(FS.readFile, [\"foo.txt\", \"utf-8\"]);\n```\n\nIf you are working with methods, instead of simple functions, you can easily\nrun in to the usual problems where passing a method to another function—like\n`Q.nfcall`—\"un-binds\" the method from its owner. To avoid this, you can either\nuse `Function.prototype.bind` or some nice shortcut methods we provide:\n\n```javascript\nreturn Q.ninvoke(redisClient, \"get\", \"user:1:id\");\nreturn Q.npost(redisClient, \"get\", [\"user:1:id\"]);\n```\n\nYou can also create reusable wrappers with `Q.denodeify` or `Q.nbind`:\n\n```javascript\nvar readFile = Q.denodeify(FS.readFile);\nreturn readFile(\"foo.txt\", \"utf-8\");\n\nvar redisClientGet = Q.nbind(redisClient.get, redisClient);\nreturn redisClientGet(\"user:1:id\");\n```\n\nFinally, if you're working with raw deferred objects, there is a\n`makeNodeResolver` method on deferreds that can be handy:\n\n```javascript\nvar deferred = Q.defer();\nFS.readFile(\"foo.txt\", \"utf-8\", deferred.makeNodeResolver());\nreturn deferred.promise;\n```\n\n### Long Stack Traces\n\nQ comes with optional support for “long stack traces,” wherein the `stack`\nproperty of `Error` rejection reasons is rewritten to be traced along\nasynchronous jumps instead of stopping at the most recent one. As an example:\n\n```js\nfunction theDepthsOfMyProgram() {\n  Q.delay(100).done(function explode() {\n    throw new Error(\"boo!\");\n  });\n}\n\ntheDepthsOfMyProgram();\n```\n\nusually would give a rather unhelpful stack trace looking something like\n\n```\nError: boo!\n    at explode (/path/to/test.js:3:11)\n    at _fulfilled (/path/to/test.js:q:54)\n    at resolvedValue.promiseDispatch.done (/path/to/q.js:823:30)\n    at makePromise.promise.promiseDispatch (/path/to/q.js:496:13)\n    at pending (/path/to/q.js:397:39)\n    at process.startup.processNextTick.process._tickCallback (node.js:244:9)\n```\n\nBut, if you turn this feature on by setting\n\n```js\nQ.longStackSupport = true;\n```\n\nthen the above code gives a nice stack trace to the tune of\n\n```\nError: boo!\n    at explode (/path/to/test.js:3:11)\nFrom previous event:\n    at theDepthsOfMyProgram (/path/to/test.js:2:16)\n    at Object.<anonymous> (/path/to/test.js:7:1)\n```\n\nNote how you can see the the function that triggered the async operation in the\nstack trace! This is very helpful for debugging, as otherwise you end up getting\nonly the first line, plus a bunch of Q internals, with no sign of where the\noperation started.\n\nThis feature does come with somewhat-serious performance and memory overhead,\nhowever. If you're working with lots of promises, or trying to scale a server\nto many users, you should probably keep it off. But in development, go for it!\n\n## Tests\n\nYou can view the results of the Q test suite [in your browser][tests]!\n\n[tests]: https://rawgithub.com/kriskowal/q/master/spec/q-spec.html\n\n## License\n\nCopyright 2009–2013 Kristopher Michael Kowal\nMIT License (enclosed)\n\n",
    9090  "readmeFilename": "README.md",
    91   "_id": "q@0.9.6",
     91  "_id": "q@0.9.7",
    9292  "dist": {
    93     "shasum": "ff68447a49ea86f1e926dea6eb7487a110c764d5"
     93    "shasum": "bebb084f592180190176960dd29862d3818f2e06"
    9494  },
    95   "_from": "q@",
    96   "_resolved": "https://registry.npmjs.org/q/-/q-0.9.6.tgz"
     95  "_from": "q@0.9.7",
     96  "_resolved": "https://registry.npmjs.org/q/-/q-0.9.7.tgz"
    9797}
  • Dev/trunk/src/node_modules/q/q.js

    r484 r489  
    9292
    9393    function flush() {
     94        /* jshint loopfunc: true */
     95
    9496        while (head.next) {
    9597            head = head.next;
     
    114116                    // listening "uncaughtException" events (as domains does).
    115117                    // Continue in next event to avoid tick recursion.
    116                     domain && domain.exit();
     118                    if (domain) {
     119                        domain.exit();
     120                    }
    117121                    setTimeout(flush, 0);
    118                     domain && domain.enter();
     122                    if (domain) {
     123                        domain.enter();
     124                    }
    119125
    120126                    throw e;
     
    173179        // http://www.nonblocking.io/2011/06/windownexttick.html
    174180        var channel = new MessageChannel();
    175         channel.port1.onmessage = flush;
     181        // At least Safari Version 6.0.5 (8536.30.1) intermittently cannot create
     182        // working message ports the first time a page loads.
     183        channel.port1.onmessage = function () {
     184            requestTick = requestPortTick;
     185            channel.port1.onmessage = flush;
     186            flush();
     187        };
     188        var requestPortTick = function () {
     189            // Opera requires us to provide a message payload, regardless of
     190            // whether we use it.
     191            channel.port2.postMessage(0);
     192        };
    176193        requestTick = function () {
    177             channel.port2.postMessage(0);
     194            setTimeout(flush, 0);
     195            requestPortTick();
    178196        };
    179197
     
    199217// See Mark Miller’s explanation of what this does.
    200218// http://wiki.ecmascript.org/doku.php?id=conventions:safe_meta_programming
     219var call = Function.call;
    201220function uncurryThis(f) {
    202     var call = Function.call;
    203221    return function () {
    204222        return call.apply(f, arguments);
     
    442460
    443461/**
    444  * Creates fulfilled promises from non-thenables,
    445  * Passes Q promises through,
    446  * Coerces other thenables to Q promises.
     462 * Constructs a promise for an immediate reference, passes promises through, or
     463 * coerces promises from different systems.
     464 * @param value immediate reference or promise
    447465 */
    448466function Q(value) {
    449     return resolve(value);
    450 }
     467    // If the object is already a Promise, return it directly.  This enables
     468    // the resolve function to both be used to created references from objects,
     469    // but to tolerably coerce non-promises to promises.
     470    if (isPromise(value)) {
     471        return value;
     472    }
     473
     474    // assimilate thenables
     475    if (isPromiseAlike(value)) {
     476        return coerce(value);
     477    } else {
     478        return fulfill(value);
     479    }
     480}
     481Q.resolve = Q;
    451482
    452483/**
     
    555586        }
    556587
    557         become(resolve(value));
     588        become(Q(value));
    558589    };
    559590
     
    616647        throw new TypeError("resolver must be a function.");
    617648    }
    618 
    619649    var deferred = defer();
    620     fcall(
    621         resolver,
    622         deferred.resolve,
    623         deferred.reject,
    624         deferred.notify
    625     ).fail(deferred.reject);
     650    try {
     651        resolver(deferred.resolve, deferred.reject, deferred.notify);
     652    } catch (reason) {
     653        deferred.reject(reason);
     654    }
    626655    return deferred.promise;
    627656}
     657
     658// XXX experimental.  This method is a way to denote that a local value is
     659// serializable and should be immediately dispatched to a remote upon request,
     660// instead of passing a reference.
     661Q.passByCopy = function (object) {
     662    //freeze(object);
     663    //passByCopies.set(object, true);
     664    return object;
     665};
     666
     667Promise.prototype.passByCopy = function () {
     668    //freeze(object);
     669    //passByCopies.set(object, true);
     670    return this;
     671};
     672
     673/**
     674 * If two promises eventually fulfill to the same value, promises that value,
     675 * but otherwise rejects.
     676 * @param x {Any*}
     677 * @param y {Any*}
     678 * @returns {Any*} a promise for x and y if they are the same, but a rejection
     679 * otherwise.
     680 *
     681 */
     682Q.join = function (x, y) {
     683    return Q(x).join(y);
     684};
     685
     686Promise.prototype.join = function (that) {
     687    return Q([this, that]).spread(function (x, y) {
     688        if (x === y) {
     689            // TODO: "===" should be Object.is or equiv
     690            return x;
     691        } else {
     692            throw new Error("Can't join: not the same: " + x + " " + y);
     693        }
     694    });
     695};
     696
     697/**
     698 * Returns a promise for the first of an array of promises to become fulfilled.
     699 * @param answers {Array[Any*]} promises to race
     700 * @returns {Any*} the first promise to be fulfilled
     701 */
     702Q.race = race;
     703function race(answerPs) {
     704    return promise(function(resolve, reject) {
     705        // Switch to this once we can assume at least ES5
     706        // answerPs.forEach(function(answerP) {
     707        //     Q(answerP).then(resolve, reject);
     708        // });
     709        // Use this in the meantime
     710        for (var i = 0, len = answerPs.length; i < len; i++) {
     711            Q(answerPs[i]).then(resolve, reject);
     712        }
     713    });
     714}
     715
     716Promise.prototype.race = function () {
     717    return this.then(Q.race);
     718};
    628719
    629720/**
     
    692783    return promise;
    693784}
     785
     786Promise.prototype.toString = function () {
     787    return "[object Promise]";
     788};
    694789
    695790Promise.prototype.then = function (fulfilled, rejected, progressed) {
     
    764859};
    765860
     861/**
     862 * Registers an observer on a promise.
     863 *
     864 * Guarantees:
     865 *
     866 * 1. that fulfilled and rejected will be called only once.
     867 * 2. that either the fulfilled callback or the rejected callback will be
     868 *    called, but not both.
     869 * 3. that fulfilled and rejected will not be called in this turn.
     870 *
     871 * @param value      promise or immediate reference to observe
     872 * @param fulfilled  function to be called with the fulfilled value
     873 * @param rejected   function to be called with the rejection exception
     874 * @param progressed function to be called on any progress notifications
     875 * @return promise for the return value from the invoked callback
     876 */
     877Q.when = when;
     878function when(value, fulfilled, rejected, progressed) {
     879    return Q(value).then(fulfilled, rejected, progressed);
     880}
     881
    766882Promise.prototype.thenResolve = function (value) {
    767     return when(this, function () { return value; });
     883    return this.then(function () { return value; });
     884};
     885
     886Q.thenResolve = function (promise, value) {
     887    return Q(promise).thenResolve(value);
    768888};
    769889
    770890Promise.prototype.thenReject = function (reason) {
    771     return when(this, function () { throw reason; });
    772 };
    773 
    774 // Chainable methods
    775 array_reduce(
    776     [
    777         "isFulfilled", "isRejected", "isPending",
    778         "dispatch",
    779         "when", "spread",
    780         "get", "set", "del", "delete",
    781         "post", "send", "mapply", "invoke", "mcall",
    782         "keys",
    783         "fapply", "fcall", "fbind",
    784         "all", "allResolved",
    785         "timeout", "delay",
    786         "catch", "finally", "fail", "fin", "progress", "done",
    787         "nfcall", "nfapply", "nfbind", "denodeify", "nbind",
    788         "npost", "nsend", "nmapply", "ninvoke", "nmcall",
    789         "nodeify"
    790     ],
    791     function (undefined, name) {
    792         Promise.prototype[name] = function () {
    793             return Q[name].apply(
    794                 Q,
    795                 [this].concat(array_slice(arguments))
    796             );
    797         };
    798     },
    799     void 0
    800 );
    801 
    802 Promise.prototype.toSource = function () {
    803     return this.toString();
    804 };
    805 
    806 Promise.prototype.toString = function () {
    807     return "[object Promise]";
     891    return this.then(function () { throw reason; });
     892};
     893
     894Q.thenReject = function (promise, reason) {
     895    return Q(promise).thenReject(reason);
    808896};
    809897
     
    855943}
    856944
     945Promise.prototype.isPending = function () {
     946    return this.inspect().state === "pending";
     947};
     948
    857949/**
    858950 * @returns whether the given object is a value or fulfilled
     
    864956}
    865957
     958Promise.prototype.isFulfilled = function () {
     959    return this.inspect().state === "fulfilled";
     960};
     961
    866962/**
    867963 * @returns whether the given object is a rejected promise.
     
    871967    return isPromise(object) && object.inspect().state === "rejected";
    872968}
     969
     970Promise.prototype.isRejected = function () {
     971    return this.inspect().state === "rejected";
     972};
    873973
    874974//// BEGIN UNHANDLED REJECTION TRACKING
     
    899999    for (var i = 0; i < unhandledReasons.length; i++) {
    9001000        var reason = unhandledReasons[i];
    901         if (reason && typeof reason.stack !== "undefined") {
    902             console.warn("Unhandled rejection reason:", reason.stack);
    903         } else {
    904             console.warn("Unhandled rejection reason (no stack):", reason);
    905         }
     1001        console.warn("Unhandled rejection reason:", reason);
    9061002    }
    9071003}
     
    9301026
    9311027    unhandledRejections.push(promise);
    932     unhandledReasons.push(reason);
     1028    if (reason && typeof reason.stack !== "undefined") {
     1029        unhandledReasons.push(reason.stack);
     1030    } else {
     1031        unhandledReasons.push("(no stack) " + reason);
     1032    }
    9331033    displayUnhandledReasons();
    9341034}
     
    10191119            }
    10201120        },
    1021         "apply": function (thisP, args) {
    1022             return value.apply(thisP, args);
     1121        "apply": function (thisp, args) {
     1122            return value.apply(thisp, args);
    10231123        },
    10241124        "keys": function () {
     
    10281128        return { state: "fulfilled", value: value };
    10291129    });
    1030 }
    1031 
    1032 /**
    1033  * Constructs a promise for an immediate reference, passes promises through, or
    1034  * coerces promises from different systems.
    1035  * @param value immediate reference or promise
    1036  */
    1037 Q.resolve = resolve;
    1038 function resolve(value) {
    1039     // If the object is already a Promise, return it directly.  This enables
    1040     // the resolve function to both be used to created references from objects,
    1041     // but to tolerably coerce non-promises to promises.
    1042     if (isPromise(value)) {
    1043         return value;
    1044     }
    1045 
    1046     // assimilate thenables
    1047     if (isPromiseAlike(value)) {
    1048         return coerce(value);
    1049     } else {
    1050         return fulfill(value);
    1051     }
    10521130}
    10531131
     
    10851163        return dispatch(object, op, args);
    10861164    }, function () {
    1087         return resolve(object).inspect();
     1165        return Q(object).inspect();
    10881166    });
    1089 }
    1090 
    1091 /**
    1092  * Registers an observer on a promise.
    1093  *
    1094  * Guarantees:
    1095  *
    1096  * 1. that fulfilled and rejected will be called only once.
    1097  * 2. that either the fulfilled callback or the rejected callback will be
    1098  *    called, but not both.
    1099  * 3. that fulfilled and rejected will not be called in this turn.
    1100  *
    1101  * @param value      promise or immediate reference to observe
    1102  * @param fulfilled  function to be called with the fulfilled value
    1103  * @param rejected   function to be called with the rejection exception
    1104  * @param progressed function to be called on any progress notifications
    1105  * @return promise for the return value from the invoked callback
    1106  */
    1107 Q.when = when;
    1108 function when(value, fulfilled, rejected, progressed) {
    1109     return Q(value).then(fulfilled, rejected, progressed);
    11101167}
    11111168
     
    11211178 */
    11221179Q.spread = spread;
    1123 function spread(promise, fulfilled, rejected) {
    1124     return when(promise, function (valuesOrPromises) {
    1125         return all(valuesOrPromises).then(function (values) {
    1126             return fulfilled.apply(void 0, values);
    1127         }, rejected);
     1180function spread(value, fulfilled, rejected) {
     1181    return Q(value).spread(fulfilled, rejected);
     1182}
     1183
     1184Promise.prototype.spread = function (fulfilled, rejected) {
     1185    return this.all().then(function (array) {
     1186        return fulfilled.apply(void 0, array);
    11281187    }, rejected);
    1129 }
     1188};
    11301189
    11311190/**
     
    11881247        }
    11891248        var generator = makeGenerator.apply(this, arguments);
    1190         var callback = continuer.bind(continuer, "send");
     1249        var callback = continuer.bind(continuer, "next");
    11911250        var errback = continuer.bind(continuer, "throw");
    11921251        return callback();
     
    12461305 *     return a + b;
    12471306 * });
    1248  * add(Q.resolve(a), Q.resolve(B));
     1307 * add(Q(a), Q(B));
    12491308 *
    12501309 * @param {function} callback The function to decorate
     
    12691328Q.dispatch = dispatch;
    12701329function dispatch(object, op, args) {
     1330    return Q(object).dispatch(op, args);
     1331}
     1332
     1333Promise.prototype.dispatch = function (op, args) {
     1334    var self = this;
    12711335    var deferred = defer();
    12721336    nextTick(function () {
    1273         resolve(object).promiseDispatch(deferred.resolve, op, args);
     1337        self.promiseDispatch(deferred.resolve, op, args);
    12741338    });
    12751339    return deferred.promise;
    1276 }
    1277 
    1278 /**
    1279  * Constructs a promise method that can be used to safely observe resolution of
    1280  * a promise for an arbitrarily named method like "propfind" in a future turn.
    1281  *
    1282  * "dispatcher" constructs methods like "get(promise, name)" and "set(promise)".
    1283  */
    1284 Q.dispatcher = dispatcher;
    1285 function dispatcher(op) {
    1286     return function (object) {
    1287         var args = array_slice(arguments, 1);
    1288         return dispatch(object, op, args);
    1289     };
    1290 }
     1340};
    12911341
    12921342/**
     
    12961346 * @return promise for the property value
    12971347 */
    1298 Q.get = dispatcher("get");
     1348Q.get = function (object, key) {
     1349    return Q(object).dispatch("get", [key]);
     1350};
     1351
     1352Promise.prototype.get = function (key) {
     1353    return this.dispatch("get", [key]);
     1354};
    12991355
    13001356/**
     
    13051361 * @return promise for the return value
    13061362 */
    1307 Q.set = dispatcher("set");
     1363Q.set = function (object, key, value) {
     1364    return Q(object).dispatch("set", [key, value]);
     1365};
     1366
     1367Promise.prototype.set = function (key, value) {
     1368    return this.dispatch("set", [key, value]);
     1369};
    13081370
    13091371/**
     
    13131375 * @return promise for the return value
    13141376 */
    1315 Q["delete"] = // XXX experimental
    1316 Q.del = dispatcher("delete");
     1377Q.del = // XXX legacy
     1378Q["delete"] = function (object, key) {
     1379    return Q(object).dispatch("delete", [key]);
     1380};
     1381
     1382Promise.prototype.del = // XXX legacy
     1383Promise.prototype["delete"] = function (key) {
     1384    return this.dispatch("delete", [key]);
     1385};
    13171386
    13181387/**
     
    13291398 */
    13301399// bound locally because it is used by other methods
    1331 var post = Q.post = dispatcher("post");
    1332 Q.mapply = post; // experimental
     1400Q.mapply = // XXX As proposed by "Redsandro"
     1401Q.post = function (object, name, args) {
     1402    return Q(object).dispatch("post", [name, args]);
     1403};
     1404
     1405Promise.prototype.mapply = // XXX As proposed by "Redsandro"
     1406Promise.prototype.post = function (name, args) {
     1407    return this.dispatch("post", [name, args]);
     1408};
    13331409
    13341410/**
     
    13391415 * @return promise for the return value
    13401416 */
    1341 Q.send = send;
    1342 Q.invoke = send; // synonyms
    1343 Q.mcall = send; // experimental
    1344 function send(value, name) {
    1345     var args = array_slice(arguments, 2);
    1346     return post(value, name, args);
    1347 }
     1417Q.send = // XXX Mark Miller's proposed parlance
     1418Q.mcall = // XXX As proposed by "Redsandro"
     1419Q.invoke = function (object, name /*...args*/) {
     1420    return Q(object).dispatch("post", [name, array_slice(arguments, 2)]);
     1421};
     1422
     1423Promise.prototype.send = // XXX Mark Miller's proposed parlance
     1424Promise.prototype.mcall = // XXX As proposed by "Redsandro"
     1425Promise.prototype.invoke = function (name /*...args*/) {
     1426    return this.dispatch("post", [name, array_slice(arguments, 1)]);
     1427};
    13481428
    13491429/**
     
    13521432 * @param args      array of application arguments
    13531433 */
    1354 Q.fapply = fapply;
    1355 function fapply(value, args) {
    1356     return dispatch(value, "apply", [void 0, args]);
    1357 }
     1434Q.fapply = function (object, args) {
     1435    return Q(object).dispatch("apply", [void 0, args]);
     1436};
     1437
     1438Promise.prototype.fapply = function (args) {
     1439    return this.dispatch("apply", [void 0, args]);
     1440};
    13581441
    13591442/**
     
    13621445 * @param ...args   array of application arguments
    13631446 */
    1364 Q["try"] = fcall; // XXX experimental
    1365 Q.fcall = fcall;
    1366 function fcall(value) {
    1367     var args = array_slice(arguments, 1);
    1368     return fapply(value, args);
    1369 }
     1447Q["try"] =
     1448Q.fcall = function (object /* ...args*/) {
     1449    return Q(object).dispatch("apply", [void 0, array_slice(arguments, 1)]);
     1450};
     1451
     1452Promise.prototype.fcall = function (/*...args*/) {
     1453    return this.dispatch("apply", [void 0, array_slice(arguments)]);
     1454};
    13701455
    13711456/**
     
    13751460 * @param ...args   array of application arguments
    13761461 */
    1377 Q.fbind = fbind;
    1378 function fbind(value) {
     1462Q.fbind = function (object /*...args*/) {
     1463    var promise = Q(object);
    13791464    var args = array_slice(arguments, 1);
    13801465    return function fbound() {
    1381         var allArgs = args.concat(array_slice(arguments));
    1382         return dispatch(value, "apply", [this, allArgs]);
     1466        return promise.dispatch("apply", [
     1467            this,
     1468            args.concat(array_slice(arguments))
     1469        ]);
    13831470    };
    1384 }
     1471};
     1472Promise.prototype.fbind = function (/*...args*/) {
     1473    var promise = this;
     1474    var args = array_slice(arguments);
     1475    return function fbound() {
     1476        return promise.dispatch("apply", [
     1477            this,
     1478            args.concat(array_slice(arguments))
     1479        ]);
     1480    };
     1481};
    13851482
    13861483/**
     
    13901487 * @return promise for the keys of the eventually settled object
    13911488 */
    1392 Q.keys = dispatcher("keys");
     1489Q.keys = function (object) {
     1490    return Q(object).dispatch("keys", []);
     1491};
     1492
     1493Promise.prototype.keys = function () {
     1494    return this.dispatch("keys", []);
     1495};
    13931496
    13941497/**
     
    14151518            } else {
    14161519                ++countDown;
    1417                 when(promise, function (value) {
    1418                     promises[index] = value;
    1419                     if (--countDown === 0) {
    1420                         deferred.resolve(promises);
     1520                when(
     1521                    promise,
     1522                    function (value) {
     1523                        promises[index] = value;
     1524                        if (--countDown === 0) {
     1525                            deferred.resolve(promises);
     1526                        }
     1527                    },
     1528                    deferred.reject,
     1529                    function (progress) {
     1530                        deferred.notify({ index: index, value: progress });
    14211531                    }
    1422                 }, deferred.reject);
     1532                );
    14231533            }
    14241534        }, void 0);
     
    14291539    });
    14301540}
     1541
     1542Promise.prototype.all = function () {
     1543    return all(this);
     1544};
    14311545
    14321546/**
     
    14421556function allResolved(promises) {
    14431557    return when(promises, function (promises) {
    1444         promises = array_map(promises, resolve);
     1558        promises = array_map(promises, Q);
    14451559        return when(all(array_map(promises, function (promise) {
    14461560            return when(promise, noop, noop);
     
    14511565}
    14521566
     1567Promise.prototype.allResolved = function () {
     1568    return allResolved(this);
     1569};
     1570
     1571/**
     1572 * @see Promise#allSettled
     1573 */
    14531574Q.allSettled = allSettled;
    1454 function allSettled(values) {
    1455     return when(values, function (values) {
    1456         return all(array_map(values, function (value, i) {
    1457             return when(
    1458                 value,
    1459                 function (fulfillmentValue) {
    1460                     values[i] = { state: "fulfilled", value: fulfillmentValue };
    1461                     return values[i];
    1462                 },
    1463                 function (reason) {
    1464                     values[i] = { state: "rejected", reason: reason };
    1465                     return values[i];
    1466                 }
    1467             );
    1468         })).thenResolve(values);
     1575function allSettled(promises) {
     1576    return Q(promises).allSettled();
     1577}
     1578
     1579/**
     1580 * Turns an array of promises into a promise for an array of their states (as
     1581 * returned by `inspect`) when they have all settled.
     1582 * @param {Array[Any*]} values an array (or promise for an array) of values (or
     1583 * promises for values)
     1584 * @returns {Array[State]} an array of states for the respective values.
     1585 */
     1586Promise.prototype.allSettled = function () {
     1587    return this.then(function (promises) {
     1588        return all(array_map(promises, function (promise) {
     1589            promise = Q(promise);
     1590            function regardless() {
     1591                return promise.inspect();
     1592            }
     1593            return promise.then(regardless, regardless);
     1594        }));
    14691595    });
    1470 }
     1596};
    14711597
    14721598/**
     
    14791605 * @returns a promise for the return value of the callback
    14801606 */
    1481 Q["catch"] = // XXX experimental
    1482 Q.fail = fail;
    1483 function fail(promise, rejected) {
    1484     return when(promise, void 0, rejected);
    1485 }
     1607Q.fail = // XXX legacy
     1608Q["catch"] = function (object, rejected) {
     1609    return Q(object).then(void 0, rejected);
     1610};
     1611
     1612Promise.prototype.fail = // XXX legacy
     1613Promise.prototype["catch"] = function (rejected) {
     1614    return this.then(void 0, rejected);
     1615};
    14861616
    14871617/**
     
    14941624 */
    14951625Q.progress = progress;
    1496 function progress(promise, progressed) {
    1497     return when(promise, void 0, void 0, progressed);
    1498 }
     1626function progress(object, progressed) {
     1627    return Q(object).then(void 0, void 0, progressed);
     1628}
     1629
     1630Promise.prototype.progress = function (progressed) {
     1631    return this.then(void 0, void 0, progressed);
     1632};
    14991633
    15001634/**
     
    15091643 * ``fin`` is done.
    15101644 */
    1511 Q["finally"] = // XXX experimental
    1512 Q.fin = fin;
    1513 function fin(promise, callback) {
    1514     return when(promise, function (value) {
    1515         return when(callback(), function () {
     1645Q.fin = // XXX legacy
     1646Q["finally"] = function (object, callback) {
     1647    return Q(object)["finally"](callback);
     1648};
     1649
     1650Promise.prototype.fin = // XXX legacy
     1651Promise.prototype["finally"] = function (callback) {
     1652    callback = Q(callback);
     1653    return this.then(function (value) {
     1654        return callback.fcall().then(function () {
    15161655            return value;
    15171656        });
    1518     }, function (exception) {
    1519         return when(callback(), function () {
    1520             return reject(exception);
     1657    }, function (reason) {
     1658        // TODO attempt to recycle the rejection with "this".
     1659        return callback.fcall().then(function () {
     1660            throw reason;
    15211661        });
    15221662    });
    1523 }
     1663};
    15241664
    15251665/**
     
    15291669 * @returns nothing
    15301670 */
    1531 Q.done = done;
    1532 function done(promise, fulfilled, rejected, progress) {
     1671Q.done = function (object, fulfilled, rejected, progress) {
     1672    return Q(object).done(fulfilled, rejected, progress);
     1673};
     1674
     1675Promise.prototype.done = function (fulfilled, rejected, progress) {
    15331676    var onUnhandledError = function (error) {
    15341677        // forward to a future turn so that ``when``
     
    15361679        nextTick(function () {
    15371680            makeStackTraceLong(error, promise);
    1538 
    15391681            if (Q.onerror) {
    15401682                Q.onerror(error);
     
    15461688
    15471689    // Avoid unnecessary `nextTick`ing via an unnecessary `when`.
    1548     var promiseToHandle = fulfilled || rejected || progress ?
    1549         when(promise, fulfilled, rejected, progress) :
    1550         promise;
     1690    var promise = fulfilled || rejected || progress ?
     1691        this.then(fulfilled, rejected, progress) :
     1692        this;
    15511693
    15521694    if (typeof process === "object" && process && process.domain) {
    15531695        onUnhandledError = process.domain.bind(onUnhandledError);
    15541696    }
    1555     fail(promiseToHandle, onUnhandledError);
    1556 }
     1697
     1698    promise.then(void 0, onUnhandledError);
     1699};
    15571700
    15581701/**
     
    15651708 * fulfilled before the timeout, otherwise rejected.
    15661709 */
    1567 Q.timeout = timeout;
    1568 function timeout(promise, ms, msg) {
     1710Q.timeout = function (object, ms, message) {
     1711    return Q(object).timeout(ms, message);
     1712};
     1713
     1714Promise.prototype.timeout = function (ms, message) {
    15691715    var deferred = defer();
    15701716    var timeoutId = setTimeout(function () {
    1571         deferred.reject(new Error(msg || "Timed out after " + ms + " ms"));
     1717        deferred.reject(new Error(message || "Timed out after " + ms + " ms"));
    15721718    }, ms);
    15731719
    1574     when(promise, function (value) {
     1720    this.then(function (value) {
    15751721        clearTimeout(timeoutId);
    15761722        deferred.resolve(value);
     
    15811727
    15821728    return deferred.promise;
    1583 }
    1584 
    1585 /**
    1586  * Returns a promise for the given value (or promised value) after some
    1587  * milliseconds.
     1729};
     1730
     1731/**
     1732 * Returns a promise for the given value (or promised value), some
     1733 * milliseconds after it resolved. Passes rejections immediately.
    15881734 * @param {Any*} promise
    15891735 * @param {Number} milliseconds
    1590  * @returns a promise for the resolution of the given promise after some
    1591  * time has elapsed.
    1592  */
    1593 Q.delay = delay;
    1594 function delay(promise, timeout) {
     1736 * @returns a promise for the resolution of the given promise after milliseconds
     1737 * time has elapsed since the resolution of the given promise.
     1738 * If the given promise rejects, that is passed immediately.
     1739 */
     1740Q.delay = function (object, timeout) {
    15951741    if (timeout === void 0) {
    1596         timeout = promise;
    1597         promise = void 0;
    1598     }
    1599 
    1600     var deferred = defer();
    1601 
    1602     when(promise, undefined, undefined, deferred.notify);
    1603     setTimeout(function () {
    1604         deferred.resolve(promise);
    1605     }, timeout);
    1606 
    1607     return deferred.promise;
    1608 }
     1742        timeout = object;
     1743        object = void 0;
     1744    }
     1745    return Q(object).delay(timeout);
     1746};
     1747
     1748Promise.prototype.delay = function (timeout) {
     1749    return this.then(function (value) {
     1750        var deferred = defer();
     1751        setTimeout(function () {
     1752            deferred.resolve(value);
     1753        }, timeout);
     1754        return deferred.promise;
     1755    });
     1756};
    16091757
    16101758/**
     
    16171765 *
    16181766 */
    1619 Q.nfapply = nfapply;
    1620 function nfapply(callback, args) {
     1767Q.nfapply = function (callback, args) {
     1768    return Q(callback).nfapply(args);
     1769};
     1770
     1771Promise.prototype.nfapply = function (args) {
     1772    var deferred = defer();
    16211773    var nodeArgs = array_slice(args);
     1774    nodeArgs.push(deferred.makeNodeResolver());
     1775    this.fapply(nodeArgs).fail(deferred.reject);
     1776    return deferred.promise;
     1777};
     1778
     1779/**
     1780 * Passes a continuation to a Node function, which is called with the given
     1781 * arguments provided individually, and returns a promise.
     1782 * @example
     1783 * Q.nfcall(FS.readFile, __filename)
     1784 * .then(function (content) {
     1785 * })
     1786 *
     1787 */
     1788Q.nfcall = function (callback /*...args*/) {
     1789    var args = array_slice(arguments, 1);
     1790    return Q(callback).nfapply(args);
     1791};
     1792
     1793Promise.prototype.nfcall = function (/*...args*/) {
     1794    var nodeArgs = array_slice(arguments);
    16221795    var deferred = defer();
    16231796    nodeArgs.push(deferred.makeNodeResolver());
    1624 
    1625     fapply(callback, nodeArgs).fail(deferred.reject);
     1797    this.fapply(nodeArgs).fail(deferred.reject);
    16261798    return deferred.promise;
    1627 }
    1628 
    1629 /**
    1630  * Passes a continuation to a Node function, which is called with the given
    1631  * arguments provided individually, and returns a promise.
    1632  *
    1633  *      Q.nfcall(FS.readFile, __filename)
    1634  *      .then(function (content) {
    1635  *      })
    1636  *
    1637  */
    1638 Q.nfcall = nfcall;
    1639 function nfcall(callback/*, ...args */) {
    1640     var nodeArgs = array_slice(arguments, 1);
    1641     var deferred = defer();
    1642     nodeArgs.push(deferred.makeNodeResolver());
    1643 
    1644     fapply(callback, nodeArgs).fail(deferred.reject);
    1645     return deferred.promise;
    1646 }
     1799};
    16471800
    16481801/**
    16491802 * Wraps a NodeJS continuation passing function and returns an equivalent
    16501803 * version that returns a promise.
    1651  *
    1652  *      Q.nfbind(FS.readFile, __filename)("utf-8")
    1653  *      .then(console.log)
    1654  *      .done()
    1655  *
    1656  */
    1657 Q.nfbind = nfbind;
    1658 Q.denodeify = Q.nfbind; // synonyms
    1659 function nfbind(callback/*, ...args */) {
     1804 * @example
     1805 * Q.nfbind(FS.readFile, __filename)("utf-8")
     1806 * .then(console.log)
     1807 * .done()
     1808 */
     1809Q.nfbind =
     1810Q.denodeify = function (callback /*...args*/) {
    16601811    var baseArgs = array_slice(arguments, 1);
    16611812    return function () {
     
    16631814        var deferred = defer();
    16641815        nodeArgs.push(deferred.makeNodeResolver());
    1665 
    1666         fapply(callback, nodeArgs).fail(deferred.reject);
     1816        Q(callback).fapply(nodeArgs).fail(deferred.reject);
    16671817        return deferred.promise;
    16681818    };
    1669 }
    1670 
    1671 Q.nbind = nbind;
    1672 function nbind(callback, thisArg /*, ... args*/) {
     1819};
     1820
     1821Promise.prototype.nfbind =
     1822Promise.prototype.denodeify = function (/*...args*/) {
     1823    var args = array_slice(arguments);
     1824    args.unshift(this);
     1825    return Q.denodeify.apply(void 0, args);
     1826};
     1827
     1828Q.nbind = function (callback, thisp /*...args*/) {
    16731829    var baseArgs = array_slice(arguments, 2);
    16741830    return function () {
     
    16761832        var deferred = defer();
    16771833        nodeArgs.push(deferred.makeNodeResolver());
    1678 
    16791834        function bound() {
    1680             return callback.apply(thisArg, arguments);
    1681         }
    1682 
    1683         fapply(bound, nodeArgs).fail(deferred.reject);
     1835            return callback.apply(thisp, arguments);
     1836        }
     1837        Q(bound).fapply(nodeArgs).fail(deferred.reject);
    16841838        return deferred.promise;
    16851839    };
    1686 }
     1840};
     1841
     1842Promise.prototype.nbind = function (/*thisp, ...args*/) {
     1843    var args = array_slice(arguments, 0);
     1844    args.unshift(this);
     1845    return Q.nbind.apply(void 0, args);
     1846};
    16871847
    16881848/**
     
    16951855 * @returns a promise for the value or error
    16961856 */
    1697 Q.npost = npost;
    1698 Q.nmapply = npost; // synonyms
    1699 function npost(object, name, args) {
     1857Q.nmapply = // XXX As proposed by "Redsandro"
     1858Q.npost = function (object, name, args) {
     1859    return Q(object).npost(name, args);
     1860};
     1861
     1862Promise.prototype.nmapply = // XXX As proposed by "Redsandro"
     1863Promise.prototype.npost = function (name, args) {
    17001864    var nodeArgs = array_slice(args || []);
    17011865    var deferred = defer();
    17021866    nodeArgs.push(deferred.makeNodeResolver());
    1703 
    1704     post(object, name, nodeArgs).fail(deferred.reject);
     1867    this.dispatch("post", [name, nodeArgs]).fail(deferred.reject);
    17051868    return deferred.promise;
    1706 }
     1869};
    17071870
    17081871/**
     
    17161879 * @returns a promise for the value or error
    17171880 */
    1718 Q.nsend = nsend;
    1719 Q.ninvoke = Q.nsend; // synonyms
    1720 Q.nmcall = Q.nsend; // synonyms
    1721 function nsend(object, name /*, ...args*/) {
     1881Q.nsend = // XXX Based on Mark Miller's proposed "send"
     1882Q.nmcall = // XXX Based on "Redsandro's" proposal
     1883Q.ninvoke = function (object, name /*...args*/) {
    17221884    var nodeArgs = array_slice(arguments, 2);
    17231885    var deferred = defer();
    17241886    nodeArgs.push(deferred.makeNodeResolver());
    1725     post(object, name, nodeArgs).fail(deferred.reject);
     1887    Q(object).dispatch("post", [name, nodeArgs]).fail(deferred.reject);
    17261888    return deferred.promise;
    1727 }
    1728 
     1889};
     1890
     1891Promise.prototype.nsend = // XXX Based on Mark Miller's proposed "send"
     1892Promise.prototype.nmcall = // XXX Based on "Redsandro's" proposal
     1893Promise.prototype.ninvoke = function (name /*...args*/) {
     1894    var nodeArgs = array_slice(arguments, 1);
     1895    var deferred = defer();
     1896    nodeArgs.push(deferred.makeNodeResolver());
     1897    this.dispatch("post", [name, nodeArgs]).fail(deferred.reject);
     1898    return deferred.promise;
     1899};
     1900
     1901/**
     1902 * If a function would like to support both Node continuation-passing-style and
     1903 * promise-returning-style, it can end its internal promise chain with
     1904 * `nodeify(nodeback)`, forwarding the optional nodeback argument.  If the user
     1905 * elects to use a nodeback, the result will be sent there.  If they do not
     1906 * pass a nodeback, they will receive the result promise.
     1907 * @param object a result (or a promise for a result)
     1908 * @param {Function} nodeback a Node.js-style callback
     1909 * @returns either the promise or nothing
     1910 */
    17291911Q.nodeify = nodeify;
    1730 function nodeify(promise, nodeback) {
     1912function nodeify(object, nodeback) {
     1913    return Q(object).nodeify(nodeback);
     1914}
     1915
     1916Promise.prototype.nodeify = function (nodeback) {
    17311917    if (nodeback) {
    1732         promise.then(function (value) {
     1918        this.then(function (value) {
    17331919            nextTick(function () {
    17341920                nodeback(null, value);
     
    17401926        });
    17411927    } else {
    1742         return promise;
    1743     }
    1744 }
     1928        return this;
     1929    }
     1930};
    17451931
    17461932// All code before this point will be filtered from stack traces.
  • Dev/trunk/src/node_modules/request/node_modules/forever-agent/index.js

    r484 r489  
    2525     
    2626      // if an error happens while we don't use the socket anyway, meh, throw the socket away
    27       function onIdleError() {
     27      var onIdleError = function() {
    2828        socket.destroy()
    2929      }
  • Dev/trunk/src/node_modules/request/node_modules/forever-agent/package.json

    r484 r489  
    77  "name": "forever-agent",
    88  "description": "HTTP Agent that keeps socket connections alive between keep-alive requests. Formerly part of mikeal/request, now a standalone module.",
    9   "version": "0.5.0",
     9  "version": "0.5.2",
    1010  "repository": {
    1111    "url": "https://github.com/mikeal/forever-agent"
     
    2424  },
    2525  "homepage": "https://github.com/mikeal/forever-agent",
    26   "_id": "forever-agent@0.5.0",
     26  "_id": "forever-agent@0.5.2",
    2727  "_from": "forever-agent@~0.5.0"
    2828}
  • Dev/trunk/src/node_modules/request/node_modules/form-data/node_modules/async/README.md

    r484 r489  
    105105
    106106* [each](#each)
     107* [eachSeries](#eachSeries)
     108* [eachLimit](#eachLimit)
    107109* [map](#map)
     110* [mapSeries](#mapSeries)
     111* [mapLimit](#mapLimit)
    108112* [filter](#filter)
     113* [filterSeries](#filterSeries)
    109114* [reject](#reject)
     115* [rejectSeries](#rejectSeries)
    110116* [reduce](#reduce)
     117* [reduceRight](#reduceRight)
    111118* [detect](#detect)
     119* [detectSeries](#detectSeries)
    112120* [sortBy](#sortBy)
    113121* [some](#some)
    114122* [every](#every)
    115123* [concat](#concat)
     124* [concatSeries](#concatSeries)
    116125
    117126### Control Flow
     
    119128* [series](#series)
    120129* [parallel](#parallel)
     130* [parallelLimit](#parallellimittasks-limit-callback)
    121131* [whilst](#whilst)
    122132* [doWhilst](#doWhilst)
     
    127137* [compose](#compose)
    128138* [applyEach](#applyEach)
     139* [applyEachSeries](#applyEachSeries)
    129140* [queue](#queue)
    130141* [cargo](#cargo)
     
    296307
    297308```js
    298 async.map(['file1','file2','file3'], 1, fs.stat, function(err, results){
     309async.mapLimit(['file1','file2','file3'], 1, fs.stat, function(err, results){
    299310    // results is now an array of stats for each file
    300311});
     
    10631074```js
    10641075async.auto({
    1065   readData: async.apply(fs.readFile, 'data.txt', 'utf-8');
     1076  readData: async.apply(fs.readFile, 'data.txt', 'utf-8')
    10661077}, callback);
    10671078```
  • Dev/trunk/src/node_modules/request/node_modules/form-data/node_modules/async/lib/async.js

    r484 r489  
    9292        async.nextTick = process.nextTick;
    9393        if (typeof setImmediate !== 'undefined') {
    94             async.setImmediate = setImmediate;
     94            async.setImmediate = function (fn) {
     95              // not a direct alias for IE10 compatibility
     96              setImmediate(fn);
     97            };
    9598        }
    9699        else {
  • Dev/trunk/src/node_modules/request/node_modules/form-data/node_modules/async/package.json

    r484 r489  
    66    "name": "Caolan McMahon"
    77  },
    8   "version": "0.2.9",
     8  "version": "0.2.10",
    99  "repository": {
    1010    "type": "git",
     
    3636    "test": "nodeunit test/test-async.js"
    3737  },
    38   "readme": "# Async.js\n\nAsync is a utility module which provides straight-forward, powerful functions\nfor working with asynchronous JavaScript. Although originally designed for\nuse with [node.js](http://nodejs.org), it can also be used directly in the\nbrowser. Also supports [component](https://github.com/component/component).\n\nAsync provides around 20 functions that include the usual 'functional'\nsuspects (map, reduce, filter, each
) as well as some common patterns\nfor asynchronous control flow (parallel, series, waterfall
). All these\nfunctions assume you follow the node.js convention of providing a single\ncallback as the last argument of your async function.\n\n\n## Quick Examples\n\n```javascript\nasync.map(['file1','file2','file3'], fs.stat, function(err, results){\n    // results is now an array of stats for each file\n});\n\nasync.filter(['file1','file2','file3'], fs.exists, function(results){\n    // results now equals an array of the existing files\n});\n\nasync.parallel([\n    function(){ ... },\n    function(){ ... }\n], callback);\n\nasync.series([\n    function(){ ... },\n    function(){ ... }\n]);\n```\n\nThere are many more functions available so take a look at the docs below for a\nfull list. This module aims to be comprehensive, so if you feel anything is\nmissing please create a GitHub issue for it.\n\n## Common Pitfalls\n\n### Binding a context to an iterator\n\nThis section is really about bind, not about async. If you are wondering how to\nmake async execute your iterators in a given context, or are confused as to why\na method of another library isn't working as an iterator, study this example:\n\n```js\n// Here is a simple object with an (unnecessarily roundabout) squaring method\nvar AsyncSquaringLibrary = {\n  squareExponent: 2,\n  square: function(number, callback){ \n    var result = Math.pow(number, this.squareExponent);\n    setTimeout(function(){\n      callback(null, result);\n    }, 200);\n  }\n};\n\nasync.map([1, 2, 3], AsyncSquaringLibrary.square, function(err, result){\n  // result is [NaN, NaN, NaN]\n  // This fails because the `this.squareExponent` expression in the square\n  // function is not evaluated in the context of AsyncSquaringLibrary, and is\n  // therefore undefined.\n});\n\nasync.map([1, 2, 3], AsyncSquaringLibrary.square.bind(AsyncSquaringLibrary), function(err, result){\n  // result is [1, 4, 9]\n  // With the help of bind we can attach a context to the iterator before\n  // passing it to async. Now the square function will be executed in its \n  // 'home' AsyncSquaringLibrary context and the value of `this.squareExponent`\n  // will be as expected.\n});\n```\n\n## Download\n\nThe source is available for download from\n[GitHub](http://github.com/caolan/async).\nAlternatively, you can install using Node Package Manager (npm):\n\n    npm install async\n\n__Development:__ [async.js](https://github.com/caolan/async/raw/master/lib/async.js) - 29.6kb Uncompressed\n\n## In the Browser\n\nSo far it's been tested in IE6, IE7, IE8, FF3.6 and Chrome 5. Usage:\n\n```html\n<script type=\"text/javascript\" src=\"async.js\"></script>\n<script type=\"text/javascript\">\n\n    async.map(data, asyncProcess, function(err, results){\n        alert(results);\n    });\n\n</script>\n```\n\n## Documentation\n\n### Collections\n\n* [each](#each)\n* [map](#map)\n* [filter](#filter)\n* [reject](#reject)\n* [reduce](#reduce)\n* [detect](#detect)\n* [sortBy](#sortBy)\n* [some](#some)\n* [every](#every)\n* [concat](#concat)\n\n### Control Flow\n\n* [series](#series)\n* [parallel](#parallel)\n* [whilst](#whilst)\n* [doWhilst](#doWhilst)\n* [until](#until)\n* [doUntil](#doUntil)\n* [forever](#forever)\n* [waterfall](#waterfall)\n* [compose](#compose)\n* [applyEach](#applyEach)\n* [queue](#queue)\n* [cargo](#cargo)\n* [auto](#auto)\n* [iterator](#iterator)\n* [apply](#apply)\n* [nextTick](#nextTick)\n* [times](#times)\n* [timesSeries](#timesSeries)\n\n### Utils\n\n* [memoize](#memoize)\n* [unmemoize](#unmemoize)\n* [log](#log)\n* [dir](#dir)\n* [noConflict](#noConflict)\n\n\n## Collections\n\n<a name=\"forEach\" />\n<a name=\"each\" />\n### each(arr, iterator, callback)\n\nApplies an iterator function to each item in an array, in parallel.\nThe iterator is called with an item from the list and a callback for when it\nhas finished. If the iterator passes an error to this callback, the main\ncallback for the each function is immediately called with the error.\n\nNote, that since this function applies the iterator to each item in parallel\nthere is no guarantee that the iterator functions will complete in order.\n\n__Arguments__\n\n* arr - An array to iterate over.\n* iterator(item, callback) - A function to apply to each item in the array.\n  The iterator is passed a callback(err) which must be called once it has \n  completed. If no error has occured, the callback should be run without \n  arguments or with an explicit null argument.\n* callback(err) - A callback which is called after all the iterator functions\n  have finished, or an error has occurred.\n\n__Example__\n\n```js\n// assuming openFiles is an array of file names and saveFile is a function\n// to save the modified contents of that file:\n\nasync.each(openFiles, saveFile, function(err){\n    // if any of the saves produced an error, err would equal that error\n});\n```\n\n---------------------------------------\n\n<a name=\"forEachSeries\" />\n<a name=\"eachSeries\" />\n### eachSeries(arr, iterator, callback)\n\nThe same as each only the iterator is applied to each item in the array in\nseries. The next iterator is only called once the current one has completed\nprocessing. This means the iterator functions will complete in order.\n\n\n---------------------------------------\n\n<a name=\"forEachLimit\" />\n<a name=\"eachLimit\" />\n### eachLimit(arr, limit, iterator, callback)\n\nThe same as each only no more than \"limit\" iterators will be simultaneously \nrunning at any time.\n\nNote that the items are not processed in batches, so there is no guarantee that\n the first \"limit\" iterator functions will complete before any others are \nstarted.\n\n__Arguments__\n\n* arr - An array to iterate over.\n* limit - The maximum number of iterators to run at any time.\n* iterator(item, callback) - A function to apply to each item in the array.\n  The iterator is passed a callback(err) which must be called once it has \n  completed. If no error has occured, the callback should be run without \n  arguments or with an explicit null argument.\n* callback(err) - A callback which is called after all the iterator functions\n  have finished, or an error has occurred.\n\n__Example__\n\n```js\n// Assume documents is an array of JSON objects and requestApi is a\n// function that interacts with a rate-limited REST api.\n\nasync.eachLimit(documents, 20, requestApi, function(err){\n    // if any of the saves produced an error, err would equal that error\n});\n```\n\n---------------------------------------\n\n<a name=\"map\" />\n### map(arr, iterator, callback)\n\nProduces a new array of values by mapping each value in the given array through\nthe iterator function. The iterator is called with an item from the array and a\ncallback for when it has finished processing. The callback takes 2 arguments, \nan error and the transformed item from the array. If the iterator passes an\nerror to this callback, the main callback for the map function is immediately\ncalled with the error.\n\nNote, that since this function applies the iterator to each item in parallel\nthere is no guarantee that the iterator functions will complete in order, however\nthe results array will be in the same order as the original array.\n\n__Arguments__\n\n* arr - An array to iterate over.\n* iterator(item, callback) - A function to apply to each item in the array.\n  The iterator is passed a callback(err, transformed) which must be called once \n  it has completed with an error (which can be null) and a transformed item.\n* callback(err, results) - A callback which is called after all the iterator\n  functions have finished, or an error has occurred. Results is an array of the\n  transformed items from the original array.\n\n__Example__\n\n```js\nasync.map(['file1','file2','file3'], fs.stat, function(err, results){\n    // results is now an array of stats for each file\n});\n```\n\n---------------------------------------\n\n<a name=\"mapSeries\" />\n### mapSeries(arr, iterator, callback)\n\nThe same as map only the iterator is applied to each item in the array in\nseries. The next iterator is only called once the current one has completed\nprocessing. The results array will be in the same order as the original.\n\n\n---------------------------------------\n\n<a name=\"mapLimit\" />\n### mapLimit(arr, limit, iterator, callback)\n\nThe same as map only no more than \"limit\" iterators will be simultaneously \nrunning at any time.\n\nNote that the items are not processed in batches, so there is no guarantee that\n the first \"limit\" iterator functions will complete before any others are \nstarted.\n\n__Arguments__\n\n* arr - An array to iterate over.\n* limit - The maximum number of iterators to run at any time.\n* iterator(item, callback) - A function to apply to each item in the array.\n  The iterator is passed a callback(err, transformed) which must be called once \n  it has completed with an error (which can be null) and a transformed item.\n* callback(err, results) - A callback which is called after all the iterator\n  functions have finished, or an error has occurred. Results is an array of the\n  transformed items from the original array.\n\n__Example__\n\n```js\nasync.map(['file1','file2','file3'], 1, fs.stat, function(err, results){\n    // results is now an array of stats for each file\n});\n```\n\n---------------------------------------\n\n<a name=\"filter\" />\n### filter(arr, iterator, callback)\n\n__Alias:__ select\n\nReturns a new array of all the values which pass an async truth test.\n_The callback for each iterator call only accepts a single argument of true or\nfalse, it does not accept an error argument first!_ This is in-line with the\nway node libraries work with truth tests like fs.exists. This operation is\nperformed in parallel, but the results array will be in the same order as the\noriginal.\n\n__Arguments__\n\n* arr - An array to iterate over.\n* iterator(item, callback) - A truth test to apply to each item in the array.\n  The iterator is passed a callback(truthValue) which must be called with a \n  boolean argument once it has completed.\n* callback(results) - A callback which is called after all the iterator\n  functions have finished.\n\n__Example__\n\n```js\nasync.filter(['file1','file2','file3'], fs.exists, function(results){\n    // results now equals an array of the existing files\n});\n```\n\n---------------------------------------\n\n<a name=\"filterSeries\" />\n### filterSeries(arr, iterator, callback)\n\n__alias:__ selectSeries\n\nThe same as filter only the iterator is applied to each item in the array in\nseries. The next iterator is only called once the current one has completed\nprocessing. The results array will be in the same order as the original.\n\n---------------------------------------\n\n<a name=\"reject\" />\n### reject(arr, iterator, callback)\n\nThe opposite of filter. Removes values that pass an async truth test.\n\n---------------------------------------\n\n<a name=\"rejectSeries\" />\n### rejectSeries(arr, iterator, callback)\n\nThe same as reject, only the iterator is applied to each item in the array\nin series.\n\n\n---------------------------------------\n\n<a name=\"reduce\" />\n### reduce(arr, memo, iterator, callback)\n\n__aliases:__ inject, foldl\n\nReduces a list of values into a single value using an async iterator to return\neach successive step. Memo is the initial state of the reduction. This\nfunction only operates in series. For performance reasons, it may make sense to\nsplit a call to this function into a parallel map, then use the normal\nArray.prototype.reduce on the results. This function is for situations where\neach step in the reduction needs to be async, if you can get the data before\nreducing it then it's probably a good idea to do so.\n\n__Arguments__\n\n* arr - An array to iterate over.\n* memo - The initial state of the reduction.\n* iterator(memo, item, callback) - A function applied to each item in the\n  array to produce the next step in the reduction. The iterator is passed a\n  callback(err, reduction) which accepts an optional error as its first \n  argument, and the state of the reduction as the second. If an error is \n  passed to the callback, the reduction is stopped and the main callback is \n  immediately called with the error.\n* callback(err, result) - A callback which is called after all the iterator\n  functions have finished. Result is the reduced value.\n\n__Example__\n\n```js\nasync.reduce([1,2,3], 0, function(memo, item, callback){\n    // pointless async:\n    process.nextTick(function(){\n        callback(null, memo + item)\n    });\n}, function(err, result){\n    // result is now equal to the last value of memo, which is 6\n});\n```\n\n---------------------------------------\n\n<a name=\"reduceRight\" />\n### reduceRight(arr, memo, iterator, callback)\n\n__Alias:__ foldr\n\nSame as reduce, only operates on the items in the array in reverse order.\n\n\n---------------------------------------\n\n<a name=\"detect\" />\n### detect(arr, iterator, callback)\n\nReturns the first value in a list that passes an async truth test. The\niterator is applied in parallel, meaning the first iterator to return true will\nfire the detect callback with that result. That means the result might not be\nthe first item in the original array (in terms of order) that passes the test.\n\nIf order within the original array is important then look at detectSeries.\n\n__Arguments__\n\n* arr - An array to iterate over.\n* iterator(item, callback) - A truth test to apply to each item in the array.\n  The iterator is passed a callback(truthValue) which must be called with a \n  boolean argument once it has completed.\n* callback(result) - A callback which is called as soon as any iterator returns\n  true, or after all the iterator functions have finished. Result will be\n  the first item in the array that passes the truth test (iterator) or the\n  value undefined if none passed.\n\n__Example__\n\n```js\nasync.detect(['file1','file2','file3'], fs.exists, function(result){\n    // result now equals the first file in the list that exists\n});\n```\n\n---------------------------------------\n\n<a name=\"detectSeries\" />\n### detectSeries(arr, iterator, callback)\n\nThe same as detect, only the iterator is applied to each item in the array\nin series. This means the result is always the first in the original array (in\nterms of array order) that passes the truth test.\n\n\n---------------------------------------\n\n<a name=\"sortBy\" />\n### sortBy(arr, iterator, callback)\n\nSorts a list by the results of running each value through an async iterator.\n\n__Arguments__\n\n* arr - An array to iterate over.\n* iterator(item, callback) - A function to apply to each item in the array.\n  The iterator is passed a callback(err, sortValue) which must be called once it\n  has completed with an error (which can be null) and a value to use as the sort\n  criteria.\n* callback(err, results) - A callback which is called after all the iterator\n  functions have finished, or an error has occurred. Results is the items from\n  the original array sorted by the values returned by the iterator calls.\n\n__Example__\n\n```js\nasync.sortBy(['file1','file2','file3'], function(file, callback){\n    fs.stat(file, function(err, stats){\n        callback(err, stats.mtime);\n    });\n}, function(err, results){\n    // results is now the original array of files sorted by\n    // modified date\n});\n```\n\n---------------------------------------\n\n<a name=\"some\" />\n### some(arr, iterator, callback)\n\n__Alias:__ any\n\nReturns true if at least one element in the array satisfies an async test.\n_The callback for each iterator call only accepts a single argument of true or\nfalse, it does not accept an error argument first!_ This is in-line with the\nway node libraries work with truth tests like fs.exists. Once any iterator\ncall returns true, the main callback is immediately called.\n\n__Arguments__\n\n* arr - An array to iterate over.\n* iterator(item, callback) - A truth test to apply to each item in the array.\n  The iterator is passed a callback(truthValue) which must be called with a \n  boolean argument once it has completed.\n* callback(result) - A callback which is called as soon as any iterator returns\n  true, or after all the iterator functions have finished. Result will be\n  either true or false depending on the values of the async tests.\n\n__Example__\n\n```js\nasync.some(['file1','file2','file3'], fs.exists, function(result){\n    // if result is true then at least one of the files exists\n});\n```\n\n---------------------------------------\n\n<a name=\"every\" />\n### every(arr, iterator, callback)\n\n__Alias:__ all\n\nReturns true if every element in the array satisfies an async test.\n_The callback for each iterator call only accepts a single argument of true or\nfalse, it does not accept an error argument first!_ This is in-line with the\nway node libraries work with truth tests like fs.exists.\n\n__Arguments__\n\n* arr - An array to iterate over.\n* iterator(item, callback) - A truth test to apply to each item in the array.\n  The iterator is passed a callback(truthValue) which must be called with a \n  boolean argument once it has completed.\n* callback(result) - A callback which is called after all the iterator\n  functions have finished. Result will be either true or false depending on\n  the values of the async tests.\n\n__Example__\n\n```js\nasync.every(['file1','file2','file3'], fs.exists, function(result){\n    // if result is true then every file exists\n});\n```\n\n---------------------------------------\n\n<a name=\"concat\" />\n### concat(arr, iterator, callback)\n\nApplies an iterator to each item in a list, concatenating the results. Returns the\nconcatenated list. The iterators are called in parallel, and the results are\nconcatenated as they return. There is no guarantee that the results array will\nbe returned in the original order of the arguments passed to the iterator function.\n\n__Arguments__\n\n* arr - An array to iterate over\n* iterator(item, callback) - A function to apply to each item in the array.\n  The iterator is passed a callback(err, results) which must be called once it \n  has completed with an error (which can be null) and an array of results.\n* callback(err, results) - A callback which is called after all the iterator\n  functions have finished, or an error has occurred. Results is an array containing\n  the concatenated results of the iterator function.\n\n__Example__\n\n```js\nasync.concat(['dir1','dir2','dir3'], fs.readdir, function(err, files){\n    // files is now a list of filenames that exist in the 3 directories\n});\n```\n\n---------------------------------------\n\n<a name=\"concatSeries\" />\n### concatSeries(arr, iterator, callback)\n\nSame as async.concat, but executes in series instead of parallel.\n\n\n## Control Flow\n\n<a name=\"series\" />\n### series(tasks, [callback])\n\nRun an array of functions in series, each one running once the previous\nfunction has completed. If any functions in the series pass an error to its\ncallback, no more functions are run and the callback for the series is\nimmediately called with the value of the error. Once the tasks have completed,\nthe results are passed to the final callback as an array.\n\nIt is also possible to use an object instead of an array. Each property will be\nrun as a function and the results will be passed to the final callback as an object\ninstead of an array. This can be a more readable way of handling results from\nasync.series.\n\n\n__Arguments__\n\n* tasks - An array or object containing functions to run, each function is passed\n  a callback(err, result) it must call on completion with an error (which can\n  be null) and an optional result value.\n* callback(err, results) - An optional callback to run once all the functions\n  have completed. This function gets a results array (or object) containing all \n  the result arguments passed to the task callbacks.\n\n__Example__\n\n```js\nasync.series([\n    function(callback){\n        // do some stuff ...\n        callback(null, 'one');\n    },\n    function(callback){\n        // do some more stuff ...\n        callback(null, 'two');\n    }\n],\n// optional callback\nfunction(err, results){\n    // results is now equal to ['one', 'two']\n});\n\n\n// an example using an object instead of an array\nasync.series({\n    one: function(callback){\n        setTimeout(function(){\n            callback(null, 1);\n        }, 200);\n    },\n    two: function(callback){\n        setTimeout(function(){\n            callback(null, 2);\n        }, 100);\n    }\n},\nfunction(err, results) {\n    // results is now equal to: {one: 1, two: 2}\n});\n```\n\n---------------------------------------\n\n<a name=\"parallel\" />\n### parallel(tasks, [callback])\n\nRun an array of functions in parallel, without waiting until the previous\nfunction has completed. If any of the functions pass an error to its\ncallback, the main callback is immediately called with the value of the error.\nOnce the tasks have completed, the results are passed to the final callback as an\narray.\n\nIt is also possible to use an object instead of an array. Each property will be\nrun as a function and the results will be passed to the final callback as an object\ninstead of an array. This can be a more readable way of handling results from\nasync.parallel.\n\n\n__Arguments__\n\n* tasks - An array or object containing functions to run, each function is passed \n  a callback(err, result) it must call on completion with an error (which can\n  be null) and an optional result value.\n* callback(err, results) - An optional callback to run once all the functions\n  have completed. This function gets a results array (or object) containing all \n  the result arguments passed to the task callbacks.\n\n__Example__\n\n```js\nasync.parallel([\n    function(callback){\n        setTimeout(function(){\n            callback(null, 'one');\n        }, 200);\n    },\n    function(callback){\n        setTimeout(function(){\n            callback(null, 'two');\n        }, 100);\n    }\n],\n// optional callback\nfunction(err, results){\n    // the results array will equal ['one','two'] even though\n    // the second function had a shorter timeout.\n});\n\n\n// an example using an object instead of an array\nasync.parallel({\n    one: function(callback){\n        setTimeout(function(){\n            callback(null, 1);\n        }, 200);\n    },\n    two: function(callback){\n        setTimeout(function(){\n            callback(null, 2);\n        }, 100);\n    }\n},\nfunction(err, results) {\n    // results is now equals to: {one: 1, two: 2}\n});\n```\n\n---------------------------------------\n\n<a name=\"parallel\" />\n### parallelLimit(tasks, limit, [callback])\n\nThe same as parallel only the tasks are executed in parallel with a maximum of \"limit\" \ntasks executing at any time.\n\nNote that the tasks are not executed in batches, so there is no guarantee that \nthe first \"limit\" tasks will complete before any others are started.\n\n__Arguments__\n\n* tasks - An array or object containing functions to run, each function is passed \n  a callback(err, result) it must call on completion with an error (which can\n  be null) and an optional result value.\n* limit - The maximum number of tasks to run at any time.\n* callback(err, results) - An optional callback to run once all the functions\n  have completed. This function gets a results array (or object) containing all \n  the result arguments passed to the task callbacks.\n\n---------------------------------------\n\n<a name=\"whilst\" />\n### whilst(test, fn, callback)\n\nRepeatedly call fn, while test returns true. Calls the callback when stopped,\nor an error occurs.\n\n__Arguments__\n\n* test() - synchronous truth test to perform before each execution of fn.\n* fn(callback) - A function to call each time the test passes. The function is\n  passed a callback(err) which must be called once it has completed with an \n  optional error argument.\n* callback(err) - A callback which is called after the test fails and repeated\n  execution of fn has stopped.\n\n__Example__\n\n```js\nvar count = 0;\n\nasync.whilst(\n    function () { return count < 5; },\n    function (callback) {\n        count++;\n        setTimeout(callback, 1000);\n    },\n    function (err) {\n        // 5 seconds have passed\n    }\n);\n```\n\n---------------------------------------\n\n<a name=\"doWhilst\" />\n### doWhilst(fn, test, callback)\n\nThe post check version of whilst. To reflect the difference in the order of operations `test` and `fn` arguments are switched. `doWhilst` is to `whilst` as `do while` is to `while` in plain JavaScript.\n\n---------------------------------------\n\n<a name=\"until\" />\n### until(test, fn, callback)\n\nRepeatedly call fn, until test returns true. Calls the callback when stopped,\nor an error occurs.\n\nThe inverse of async.whilst.\n\n---------------------------------------\n\n<a name=\"doUntil\" />\n### doUntil(fn, test, callback)\n\nLike doWhilst except the test is inverted. Note the argument ordering differs from `until`.\n\n---------------------------------------\n\n<a name=\"forever\" />\n### forever(fn, callback)\n\nCalls the asynchronous function 'fn' repeatedly, in series, indefinitely.\nIf an error is passed to fn's callback then 'callback' is called with the\nerror, otherwise it will never be called.\n\n---------------------------------------\n\n<a name=\"waterfall\" />\n### waterfall(tasks, [callback])\n\nRuns an array of functions in series, each passing their results to the next in\nthe array. However, if any of the functions pass an error to the callback, the\nnext function is not executed and the main callback is immediately called with\nthe error.\n\n__Arguments__\n\n* tasks - An array of functions to run, each function is passed a \n  callback(err, result1, result2, ...) it must call on completion. The first\n  argument is an error (which can be null) and any further arguments will be \n  passed as arguments in order to the next task.\n* callback(err, [results]) - An optional callback to run once all the functions\n  have completed. This will be passed the results of the last task's callback.\n\n\n\n__Example__\n\n```js\nasync.waterfall([\n    function(callback){\n        callback(null, 'one', 'two');\n    },\n    function(arg1, arg2, callback){\n        callback(null, 'three');\n    },\n    function(arg1, callback){\n        // arg1 now equals 'three'\n        callback(null, 'done');\n    }\n], function (err, result) {\n   // result now equals 'done'    \n});\n```\n\n---------------------------------------\n<a name=\"compose\" />\n### compose(fn1, fn2...)\n\nCreates a function which is a composition of the passed asynchronous\nfunctions. Each function consumes the return value of the function that\nfollows. Composing functions f(), g() and h() would produce the result of\nf(g(h())), only this version uses callbacks to obtain the return values.\n\nEach function is executed with the `this` binding of the composed function.\n\n__Arguments__\n\n* functions... - the asynchronous functions to compose\n\n\n__Example__\n\n```js\nfunction add1(n, callback) {\n    setTimeout(function () {\n        callback(null, n + 1);\n    }, 10);\n}\n\nfunction mul3(n, callback) {\n    setTimeout(function () {\n        callback(null, n * 3);\n    }, 10);\n}\n\nvar add1mul3 = async.compose(mul3, add1);\n\nadd1mul3(4, function (err, result) {\n   // result now equals 15\n});\n```\n\n---------------------------------------\n<a name=\"applyEach\" />\n### applyEach(fns, args..., callback)\n\nApplies the provided arguments to each function in the array, calling the\ncallback after all functions have completed. If you only provide the first\nargument then it will return a function which lets you pass in the\narguments as if it were a single function call.\n\n__Arguments__\n\n* fns - the asynchronous functions to all call with the same arguments\n* args... - any number of separate arguments to pass to the function\n* callback - the final argument should be the callback, called when all\n  functions have completed processing\n\n\n__Example__\n\n```js\nasync.applyEach([enableSearch, updateSchema], 'bucket', callback);\n\n// partial application example:\nasync.each(\n    buckets,\n    async.applyEach([enableSearch, updateSchema]),\n    callback\n);\n```\n\n---------------------------------------\n\n<a name=\"applyEachSeries\" />\n### applyEachSeries(arr, iterator, callback)\n\nThe same as applyEach only the functions are applied in series.\n\n---------------------------------------\n\n<a name=\"queue\" />\n### queue(worker, concurrency)\n\nCreates a queue object with the specified concurrency. Tasks added to the\nqueue will be processed in parallel (up to the concurrency limit). If all\nworkers are in progress, the task is queued until one is available. Once\na worker has completed a task, the task's callback is called.\n\n__Arguments__\n\n* worker(task, callback) - An asynchronous function for processing a queued\n  task, which must call its callback(err) argument when finished, with an \n  optional error as an argument.\n* concurrency - An integer for determining how many worker functions should be\n  run in parallel.\n\n__Queue objects__\n\nThe queue object returned by this function has the following properties and\nmethods:\n\n* length() - a function returning the number of items waiting to be processed.\n* concurrency - an integer for determining how many worker functions should be\n  run in parallel. This property can be changed after a queue is created to\n  alter the concurrency on-the-fly.\n* push(task, [callback]) - add a new task to the queue, the callback is called\n  once the worker has finished processing the task.\n  instead of a single task, an array of tasks can be submitted. the respective callback is used for every task in the list.\n* unshift(task, [callback]) - add a new task to the front of the queue.\n* saturated - a callback that is called when the queue length hits the concurrency and further tasks will be queued\n* empty - a callback that is called when the last item from the queue is given to a worker\n* drain - a callback that is called when the last item from the queue has returned from the worker\n\n__Example__\n\n```js\n// create a queue object with concurrency 2\n\nvar q = async.queue(function (task, callback) {\n    console.log('hello ' + task.name);\n    callback();\n}, 2);\n\n\n// assign a callback\nq.drain = function() {\n    console.log('all items have been processed');\n}\n\n// add some items to the queue\n\nq.push({name: 'foo'}, function (err) {\n    console.log('finished processing foo');\n});\nq.push({name: 'bar'}, function (err) {\n    console.log('finished processing bar');\n});\n\n// add some items to the queue (batch-wise)\n\nq.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function (err) {\n    console.log('finished processing bar');\n});\n\n// add some items to the front of the queue\n\nq.unshift({name: 'bar'}, function (err) {\n    console.log('finished processing bar');\n});\n```\n\n---------------------------------------\n\n<a name=\"cargo\" />\n### cargo(worker, [payload])\n\nCreates a cargo object with the specified payload. Tasks added to the\ncargo will be processed altogether (up to the payload limit). If the\nworker is in progress, the task is queued until it is available. Once\nthe worker has completed some tasks, each callback of those tasks is called.\n\n__Arguments__\n\n* worker(tasks, callback) - An asynchronous function for processing an array of\n  queued tasks, which must call its callback(err) argument when finished, with \n  an optional error as an argument.\n* payload - An optional integer for determining how many tasks should be\n  processed per round; if omitted, the default is unlimited.\n\n__Cargo objects__\n\nThe cargo object returned by this function has the following properties and\nmethods:\n\n* length() - a function returning the number of items waiting to be processed.\n* payload - an integer for determining how many tasks should be\n  process per round. This property can be changed after a cargo is created to\n  alter the payload on-the-fly.\n* push(task, [callback]) - add a new task to the queue, the callback is called\n  once the worker has finished processing the task.\n  instead of a single task, an array of tasks can be submitted. the respective callback is used for every task in the list.\n* saturated - a callback that is called when the queue length hits the concurrency and further tasks will be queued\n* empty - a callback that is called when the last item from the queue is given to a worker\n* drain - a callback that is called when the last item from the queue has returned from the worker\n\n__Example__\n\n```js\n// create a cargo object with payload 2\n\nvar cargo = async.cargo(function (tasks, callback) {\n    for(var i=0; i<tasks.length; i++){\n      console.log('hello ' + tasks[i].name);\n    }\n    callback();\n}, 2);\n\n\n// add some items\n\ncargo.push({name: 'foo'}, function (err) {\n    console.log('finished processing foo');\n});\ncargo.push({name: 'bar'}, function (err) {\n    console.log('finished processing bar');\n});\ncargo.push({name: 'baz'}, function (err) {\n    console.log('finished processing baz');\n});\n```\n\n---------------------------------------\n\n<a name=\"auto\" />\n### auto(tasks, [callback])\n\nDetermines the best order for running functions based on their requirements.\nEach function can optionally depend on other functions being completed first,\nand each function is run as soon as its requirements are satisfied. If any of\nthe functions pass an error to their callback, that function will not complete\n(so any other functions depending on it will not run) and the main callback\nwill be called immediately with the error. Functions also receive an object\ncontaining the results of functions which have completed so far.\n\nNote, all functions are called with a results object as a second argument, \nso it is unsafe to pass functions in the tasks object which cannot handle the\nextra argument. For example, this snippet of code:\n\n```js\nasync.auto({\n  readData: async.apply(fs.readFile, 'data.txt', 'utf-8');\n}, callback);\n```\n\nwill have the effect of calling readFile with the results object as the last\nargument, which will fail:\n\n```js\nfs.readFile('data.txt', 'utf-8', cb, {});\n```\n\nInstead, wrap the call to readFile in a function which does not forward the \nresults object:\n\n```js\nasync.auto({\n  readData: function(cb, results){\n    fs.readFile('data.txt', 'utf-8', cb);\n  }\n}, callback);\n```\n\n__Arguments__\n\n* tasks - An object literal containing named functions or an array of\n  requirements, with the function itself the last item in the array. The key\n  used for each function or array is used when specifying requirements. The \n  function receives two arguments: (1) a callback(err, result) which must be \n  called when finished, passing an error (which can be null) and the result of \n  the function's execution, and (2) a results object, containing the results of\n  the previously executed functions.\n* callback(err, results) - An optional callback which is called when all the\n  tasks have been completed. The callback will receive an error as an argument\n  if any tasks pass an error to their callback. Results will always be passed\n\tbut if an error occurred, no other tasks will be performed, and the results\n\tobject will only contain partial results.\n  \n\n__Example__\n\n```js\nasync.auto({\n    get_data: function(callback){\n        // async code to get some data\n    },\n    make_folder: function(callback){\n        // async code to create a directory to store a file in\n        // this is run at the same time as getting the data\n    },\n    write_file: ['get_data', 'make_folder', function(callback){\n        // once there is some data and the directory exists,\n        // write the data to a file in the directory\n        callback(null, filename);\n    }],\n    email_link: ['write_file', function(callback, results){\n        // once the file is written let's email a link to it...\n        // results.write_file contains the filename returned by write_file.\n    }]\n});\n```\n\nThis is a fairly trivial example, but to do this using the basic parallel and\nseries functions would look like this:\n\n```js\nasync.parallel([\n    function(callback){\n        // async code to get some data\n    },\n    function(callback){\n        // async code to create a directory to store a file in\n        // this is run at the same time as getting the data\n    }\n],\nfunction(err, results){\n    async.series([\n        function(callback){\n            // once there is some data and the directory exists,\n            // write the data to a file in the directory\n        },\n        function(callback){\n            // once the file is written let's email a link to it...\n        }\n    ]);\n});\n```\n\nFor a complicated series of async tasks using the auto function makes adding\nnew tasks much easier and makes the code more readable.\n\n\n---------------------------------------\n\n<a name=\"iterator\" />\n### iterator(tasks)\n\nCreates an iterator function which calls the next function in the array,\nreturning a continuation to call the next one after that. It's also possible to\n'peek' the next iterator by doing iterator.next().\n\nThis function is used internally by the async module but can be useful when\nyou want to manually control the flow of functions in series.\n\n__Arguments__\n\n* tasks - An array of functions to run.\n\n__Example__\n\n```js\nvar iterator = async.iterator([\n    function(){ sys.p('one'); },\n    function(){ sys.p('two'); },\n    function(){ sys.p('three'); }\n]);\n\nnode> var iterator2 = iterator();\n'one'\nnode> var iterator3 = iterator2();\n'two'\nnode> iterator3();\n'three'\nnode> var nextfn = iterator2.next();\nnode> nextfn();\n'three'\n```\n\n---------------------------------------\n\n<a name=\"apply\" />\n### apply(function, arguments..)\n\nCreates a continuation function with some arguments already applied, a useful\nshorthand when combined with other control flow functions. Any arguments\npassed to the returned function are added to the arguments originally passed\nto apply.\n\n__Arguments__\n\n* function - The function you want to eventually apply all arguments to.\n* arguments... - Any number of arguments to automatically apply when the\n  continuation is called.\n\n__Example__\n\n```js\n// using apply\n\nasync.parallel([\n    async.apply(fs.writeFile, 'testfile1', 'test1'),\n    async.apply(fs.writeFile, 'testfile2', 'test2'),\n]);\n\n\n// the same process without using apply\n\nasync.parallel([\n    function(callback){\n        fs.writeFile('testfile1', 'test1', callback);\n    },\n    function(callback){\n        fs.writeFile('testfile2', 'test2', callback);\n    }\n]);\n```\n\nIt's possible to pass any number of additional arguments when calling the\ncontinuation:\n\n```js\nnode> var fn = async.apply(sys.puts, 'one');\nnode> fn('two', 'three');\none\ntwo\nthree\n```\n\n---------------------------------------\n\n<a name=\"nextTick\" />\n### nextTick(callback)\n\nCalls the callback on a later loop around the event loop. In node.js this just\ncalls process.nextTick, in the browser it falls back to setImmediate(callback)\nif available, otherwise setTimeout(callback, 0), which means other higher priority\nevents may precede the execution of the callback.\n\nThis is used internally for browser-compatibility purposes.\n\n__Arguments__\n\n* callback - The function to call on a later loop around the event loop.\n\n__Example__\n\n```js\nvar call_order = [];\nasync.nextTick(function(){\n    call_order.push('two');\n    // call_order now equals ['one','two']\n});\ncall_order.push('one')\n```\n\n<a name=\"times\" />\n### times(n, callback)\n\nCalls the callback n times and accumulates results in the same manner\nyou would use with async.map.\n\n__Arguments__\n\n* n - The number of times to run the function.\n* callback - The function to call n times.\n\n__Example__\n\n```js\n// Pretend this is some complicated async factory\nvar createUser = function(id, callback) {\n  callback(null, {\n    id: 'user' + id\n  })\n}\n// generate 5 users\nasync.times(5, function(n, next){\n    createUser(n, function(err, user) {\n      next(err, user)\n    })\n}, function(err, users) {\n  // we should now have 5 users\n});\n```\n\n<a name=\"timesSeries\" />\n### timesSeries(n, callback)\n\nThe same as times only the iterator is applied to each item in the array in\nseries. The next iterator is only called once the current one has completed\nprocessing. The results array will be in the same order as the original.\n\n\n## Utils\n\n<a name=\"memoize\" />\n### memoize(fn, [hasher])\n\nCaches the results of an async function. When creating a hash to store function\nresults against, the callback is omitted from the hash and an optional hash\nfunction can be used.\n\nThe cache of results is exposed as the `memo` property of the function returned\nby `memoize`.\n\n__Arguments__\n\n* fn - the function you to proxy and cache results from.\n* hasher - an optional function for generating a custom hash for storing\n  results, it has all the arguments applied to it apart from the callback, and\n  must be synchronous.\n\n__Example__\n\n```js\nvar slow_fn = function (name, callback) {\n    // do something\n    callback(null, result);\n};\nvar fn = async.memoize(slow_fn);\n\n// fn can now be used as if it were slow_fn\nfn('some name', function () {\n    // callback\n});\n```\n\n<a name=\"unmemoize\" />\n### unmemoize(fn)\n\nUndoes a memoized function, reverting it to the original, unmemoized\nform. Comes handy in tests.\n\n__Arguments__\n\n* fn - the memoized function\n\n<a name=\"log\" />\n### log(function, arguments)\n\nLogs the result of an async function to the console. Only works in node.js or\nin browsers that support console.log and console.error (such as FF and Chrome).\nIf multiple arguments are returned from the async function, console.log is\ncalled on each argument in order.\n\n__Arguments__\n\n* function - The function you want to eventually apply all arguments to.\n* arguments... - Any number of arguments to apply to the function.\n\n__Example__\n\n```js\nvar hello = function(name, callback){\n    setTimeout(function(){\n        callback(null, 'hello ' + name);\n    }, 1000);\n};\n```\n```js\nnode> async.log(hello, 'world');\n'hello world'\n```\n\n---------------------------------------\n\n<a name=\"dir\" />\n### dir(function, arguments)\n\nLogs the result of an async function to the console using console.dir to\ndisplay the properties of the resulting object. Only works in node.js or\nin browsers that support console.dir and console.error (such as FF and Chrome).\nIf multiple arguments are returned from the async function, console.dir is\ncalled on each argument in order.\n\n__Arguments__\n\n* function - The function you want to eventually apply all arguments to.\n* arguments... - Any number of arguments to apply to the function.\n\n__Example__\n\n```js\nvar hello = function(name, callback){\n    setTimeout(function(){\n        callback(null, {hello: name});\n    }, 1000);\n};\n```\n```js\nnode> async.dir(hello, 'world');\n{hello: 'world'}\n```\n\n---------------------------------------\n\n<a name=\"noConflict\" />\n### noConflict()\n\nChanges the value of async back to its original value, returning a reference to the\nasync object.\n",
     38  "readme": "# Async.js\n\nAsync is a utility module which provides straight-forward, powerful functions\nfor working with asynchronous JavaScript. Although originally designed for\nuse with [node.js](http://nodejs.org), it can also be used directly in the\nbrowser. Also supports [component](https://github.com/component/component).\n\nAsync provides around 20 functions that include the usual 'functional'\nsuspects (map, reduce, filter, each
) as well as some common patterns\nfor asynchronous control flow (parallel, series, waterfall
). All these\nfunctions assume you follow the node.js convention of providing a single\ncallback as the last argument of your async function.\n\n\n## Quick Examples\n\n```javascript\nasync.map(['file1','file2','file3'], fs.stat, function(err, results){\n    // results is now an array of stats for each file\n});\n\nasync.filter(['file1','file2','file3'], fs.exists, function(results){\n    // results now equals an array of the existing files\n});\n\nasync.parallel([\n    function(){ ... },\n    function(){ ... }\n], callback);\n\nasync.series([\n    function(){ ... },\n    function(){ ... }\n]);\n```\n\nThere are many more functions available so take a look at the docs below for a\nfull list. This module aims to be comprehensive, so if you feel anything is\nmissing please create a GitHub issue for it.\n\n## Common Pitfalls\n\n### Binding a context to an iterator\n\nThis section is really about bind, not about async. If you are wondering how to\nmake async execute your iterators in a given context, or are confused as to why\na method of another library isn't working as an iterator, study this example:\n\n```js\n// Here is a simple object with an (unnecessarily roundabout) squaring method\nvar AsyncSquaringLibrary = {\n  squareExponent: 2,\n  square: function(number, callback){ \n    var result = Math.pow(number, this.squareExponent);\n    setTimeout(function(){\n      callback(null, result);\n    }, 200);\n  }\n};\n\nasync.map([1, 2, 3], AsyncSquaringLibrary.square, function(err, result){\n  // result is [NaN, NaN, NaN]\n  // This fails because the `this.squareExponent` expression in the square\n  // function is not evaluated in the context of AsyncSquaringLibrary, and is\n  // therefore undefined.\n});\n\nasync.map([1, 2, 3], AsyncSquaringLibrary.square.bind(AsyncSquaringLibrary), function(err, result){\n  // result is [1, 4, 9]\n  // With the help of bind we can attach a context to the iterator before\n  // passing it to async. Now the square function will be executed in its \n  // 'home' AsyncSquaringLibrary context and the value of `this.squareExponent`\n  // will be as expected.\n});\n```\n\n## Download\n\nThe source is available for download from\n[GitHub](http://github.com/caolan/async).\nAlternatively, you can install using Node Package Manager (npm):\n\n    npm install async\n\n__Development:__ [async.js](https://github.com/caolan/async/raw/master/lib/async.js) - 29.6kb Uncompressed\n\n## In the Browser\n\nSo far it's been tested in IE6, IE7, IE8, FF3.6 and Chrome 5. Usage:\n\n```html\n<script type=\"text/javascript\" src=\"async.js\"></script>\n<script type=\"text/javascript\">\n\n    async.map(data, asyncProcess, function(err, results){\n        alert(results);\n    });\n\n</script>\n```\n\n## Documentation\n\n### Collections\n\n* [each](#each)\n* [eachSeries](#eachSeries)\n* [eachLimit](#eachLimit)\n* [map](#map)\n* [mapSeries](#mapSeries)\n* [mapLimit](#mapLimit)\n* [filter](#filter)\n* [filterSeries](#filterSeries)\n* [reject](#reject)\n* [rejectSeries](#rejectSeries)\n* [reduce](#reduce)\n* [reduceRight](#reduceRight)\n* [detect](#detect)\n* [detectSeries](#detectSeries)\n* [sortBy](#sortBy)\n* [some](#some)\n* [every](#every)\n* [concat](#concat)\n* [concatSeries](#concatSeries)\n\n### Control Flow\n\n* [series](#series)\n* [parallel](#parallel)\n* [parallelLimit](#parallellimittasks-limit-callback)\n* [whilst](#whilst)\n* [doWhilst](#doWhilst)\n* [until](#until)\n* [doUntil](#doUntil)\n* [forever](#forever)\n* [waterfall](#waterfall)\n* [compose](#compose)\n* [applyEach](#applyEach)\n* [applyEachSeries](#applyEachSeries)\n* [queue](#queue)\n* [cargo](#cargo)\n* [auto](#auto)\n* [iterator](#iterator)\n* [apply](#apply)\n* [nextTick](#nextTick)\n* [times](#times)\n* [timesSeries](#timesSeries)\n\n### Utils\n\n* [memoize](#memoize)\n* [unmemoize](#unmemoize)\n* [log](#log)\n* [dir](#dir)\n* [noConflict](#noConflict)\n\n\n## Collections\n\n<a name=\"forEach\" />\n<a name=\"each\" />\n### each(arr, iterator, callback)\n\nApplies an iterator function to each item in an array, in parallel.\nThe iterator is called with an item from the list and a callback for when it\nhas finished. If the iterator passes an error to this callback, the main\ncallback for the each function is immediately called with the error.\n\nNote, that since this function applies the iterator to each item in parallel\nthere is no guarantee that the iterator functions will complete in order.\n\n__Arguments__\n\n* arr - An array to iterate over.\n* iterator(item, callback) - A function to apply to each item in the array.\n  The iterator is passed a callback(err) which must be called once it has \n  completed. If no error has occured, the callback should be run without \n  arguments or with an explicit null argument.\n* callback(err) - A callback which is called after all the iterator functions\n  have finished, or an error has occurred.\n\n__Example__\n\n```js\n// assuming openFiles is an array of file names and saveFile is a function\n// to save the modified contents of that file:\n\nasync.each(openFiles, saveFile, function(err){\n    // if any of the saves produced an error, err would equal that error\n});\n```\n\n---------------------------------------\n\n<a name=\"forEachSeries\" />\n<a name=\"eachSeries\" />\n### eachSeries(arr, iterator, callback)\n\nThe same as each only the iterator is applied to each item in the array in\nseries. The next iterator is only called once the current one has completed\nprocessing. This means the iterator functions will complete in order.\n\n\n---------------------------------------\n\n<a name=\"forEachLimit\" />\n<a name=\"eachLimit\" />\n### eachLimit(arr, limit, iterator, callback)\n\nThe same as each only no more than \"limit\" iterators will be simultaneously \nrunning at any time.\n\nNote that the items are not processed in batches, so there is no guarantee that\n the first \"limit\" iterator functions will complete before any others are \nstarted.\n\n__Arguments__\n\n* arr - An array to iterate over.\n* limit - The maximum number of iterators to run at any time.\n* iterator(item, callback) - A function to apply to each item in the array.\n  The iterator is passed a callback(err) which must be called once it has \n  completed. If no error has occured, the callback should be run without \n  arguments or with an explicit null argument.\n* callback(err) - A callback which is called after all the iterator functions\n  have finished, or an error has occurred.\n\n__Example__\n\n```js\n// Assume documents is an array of JSON objects and requestApi is a\n// function that interacts with a rate-limited REST api.\n\nasync.eachLimit(documents, 20, requestApi, function(err){\n    // if any of the saves produced an error, err would equal that error\n});\n```\n\n---------------------------------------\n\n<a name=\"map\" />\n### map(arr, iterator, callback)\n\nProduces a new array of values by mapping each value in the given array through\nthe iterator function. The iterator is called with an item from the array and a\ncallback for when it has finished processing. The callback takes 2 arguments, \nan error and the transformed item from the array. If the iterator passes an\nerror to this callback, the main callback for the map function is immediately\ncalled with the error.\n\nNote, that since this function applies the iterator to each item in parallel\nthere is no guarantee that the iterator functions will complete in order, however\nthe results array will be in the same order as the original array.\n\n__Arguments__\n\n* arr - An array to iterate over.\n* iterator(item, callback) - A function to apply to each item in the array.\n  The iterator is passed a callback(err, transformed) which must be called once \n  it has completed with an error (which can be null) and a transformed item.\n* callback(err, results) - A callback which is called after all the iterator\n  functions have finished, or an error has occurred. Results is an array of the\n  transformed items from the original array.\n\n__Example__\n\n```js\nasync.map(['file1','file2','file3'], fs.stat, function(err, results){\n    // results is now an array of stats for each file\n});\n```\n\n---------------------------------------\n\n<a name=\"mapSeries\" />\n### mapSeries(arr, iterator, callback)\n\nThe same as map only the iterator is applied to each item in the array in\nseries. The next iterator is only called once the current one has completed\nprocessing. The results array will be in the same order as the original.\n\n\n---------------------------------------\n\n<a name=\"mapLimit\" />\n### mapLimit(arr, limit, iterator, callback)\n\nThe same as map only no more than \"limit\" iterators will be simultaneously \nrunning at any time.\n\nNote that the items are not processed in batches, so there is no guarantee that\n the first \"limit\" iterator functions will complete before any others are \nstarted.\n\n__Arguments__\n\n* arr - An array to iterate over.\n* limit - The maximum number of iterators to run at any time.\n* iterator(item, callback) - A function to apply to each item in the array.\n  The iterator is passed a callback(err, transformed) which must be called once \n  it has completed with an error (which can be null) and a transformed item.\n* callback(err, results) - A callback which is called after all the iterator\n  functions have finished, or an error has occurred. Results is an array of the\n  transformed items from the original array.\n\n__Example__\n\n```js\nasync.mapLimit(['file1','file2','file3'], 1, fs.stat, function(err, results){\n    // results is now an array of stats for each file\n});\n```\n\n---------------------------------------\n\n<a name=\"filter\" />\n### filter(arr, iterator, callback)\n\n__Alias:__ select\n\nReturns a new array of all the values which pass an async truth test.\n_The callback for each iterator call only accepts a single argument of true or\nfalse, it does not accept an error argument first!_ This is in-line with the\nway node libraries work with truth tests like fs.exists. This operation is\nperformed in parallel, but the results array will be in the same order as the\noriginal.\n\n__Arguments__\n\n* arr - An array to iterate over.\n* iterator(item, callback) - A truth test to apply to each item in the array.\n  The iterator is passed a callback(truthValue) which must be called with a \n  boolean argument once it has completed.\n* callback(results) - A callback which is called after all the iterator\n  functions have finished.\n\n__Example__\n\n```js\nasync.filter(['file1','file2','file3'], fs.exists, function(results){\n    // results now equals an array of the existing files\n});\n```\n\n---------------------------------------\n\n<a name=\"filterSeries\" />\n### filterSeries(arr, iterator, callback)\n\n__alias:__ selectSeries\n\nThe same as filter only the iterator is applied to each item in the array in\nseries. The next iterator is only called once the current one has completed\nprocessing. The results array will be in the same order as the original.\n\n---------------------------------------\n\n<a name=\"reject\" />\n### reject(arr, iterator, callback)\n\nThe opposite of filter. Removes values that pass an async truth test.\n\n---------------------------------------\n\n<a name=\"rejectSeries\" />\n### rejectSeries(arr, iterator, callback)\n\nThe same as reject, only the iterator is applied to each item in the array\nin series.\n\n\n---------------------------------------\n\n<a name=\"reduce\" />\n### reduce(arr, memo, iterator, callback)\n\n__aliases:__ inject, foldl\n\nReduces a list of values into a single value using an async iterator to return\neach successive step. Memo is the initial state of the reduction. This\nfunction only operates in series. For performance reasons, it may make sense to\nsplit a call to this function into a parallel map, then use the normal\nArray.prototype.reduce on the results. This function is for situations where\neach step in the reduction needs to be async, if you can get the data before\nreducing it then it's probably a good idea to do so.\n\n__Arguments__\n\n* arr - An array to iterate over.\n* memo - The initial state of the reduction.\n* iterator(memo, item, callback) - A function applied to each item in the\n  array to produce the next step in the reduction. The iterator is passed a\n  callback(err, reduction) which accepts an optional error as its first \n  argument, and the state of the reduction as the second. If an error is \n  passed to the callback, the reduction is stopped and the main callback is \n  immediately called with the error.\n* callback(err, result) - A callback which is called after all the iterator\n  functions have finished. Result is the reduced value.\n\n__Example__\n\n```js\nasync.reduce([1,2,3], 0, function(memo, item, callback){\n    // pointless async:\n    process.nextTick(function(){\n        callback(null, memo + item)\n    });\n}, function(err, result){\n    // result is now equal to the last value of memo, which is 6\n});\n```\n\n---------------------------------------\n\n<a name=\"reduceRight\" />\n### reduceRight(arr, memo, iterator, callback)\n\n__Alias:__ foldr\n\nSame as reduce, only operates on the items in the array in reverse order.\n\n\n---------------------------------------\n\n<a name=\"detect\" />\n### detect(arr, iterator, callback)\n\nReturns the first value in a list that passes an async truth test. The\niterator is applied in parallel, meaning the first iterator to return true will\nfire the detect callback with that result. That means the result might not be\nthe first item in the original array (in terms of order) that passes the test.\n\nIf order within the original array is important then look at detectSeries.\n\n__Arguments__\n\n* arr - An array to iterate over.\n* iterator(item, callback) - A truth test to apply to each item in the array.\n  The iterator is passed a callback(truthValue) which must be called with a \n  boolean argument once it has completed.\n* callback(result) - A callback which is called as soon as any iterator returns\n  true, or after all the iterator functions have finished. Result will be\n  the first item in the array that passes the truth test (iterator) or the\n  value undefined if none passed.\n\n__Example__\n\n```js\nasync.detect(['file1','file2','file3'], fs.exists, function(result){\n    // result now equals the first file in the list that exists\n});\n```\n\n---------------------------------------\n\n<a name=\"detectSeries\" />\n### detectSeries(arr, iterator, callback)\n\nThe same as detect, only the iterator is applied to each item in the array\nin series. This means the result is always the first in the original array (in\nterms of array order) that passes the truth test.\n\n\n---------------------------------------\n\n<a name=\"sortBy\" />\n### sortBy(arr, iterator, callback)\n\nSorts a list by the results of running each value through an async iterator.\n\n__Arguments__\n\n* arr - An array to iterate over.\n* iterator(item, callback) - A function to apply to each item in the array.\n  The iterator is passed a callback(err, sortValue) which must be called once it\n  has completed with an error (which can be null) and a value to use as the sort\n  criteria.\n* callback(err, results) - A callback which is called after all the iterator\n  functions have finished, or an error has occurred. Results is the items from\n  the original array sorted by the values returned by the iterator calls.\n\n__Example__\n\n```js\nasync.sortBy(['file1','file2','file3'], function(file, callback){\n    fs.stat(file, function(err, stats){\n        callback(err, stats.mtime);\n    });\n}, function(err, results){\n    // results is now the original array of files sorted by\n    // modified date\n});\n```\n\n---------------------------------------\n\n<a name=\"some\" />\n### some(arr, iterator, callback)\n\n__Alias:__ any\n\nReturns true if at least one element in the array satisfies an async test.\n_The callback for each iterator call only accepts a single argument of true or\nfalse, it does not accept an error argument first!_ This is in-line with the\nway node libraries work with truth tests like fs.exists. Once any iterator\ncall returns true, the main callback is immediately called.\n\n__Arguments__\n\n* arr - An array to iterate over.\n* iterator(item, callback) - A truth test to apply to each item in the array.\n  The iterator is passed a callback(truthValue) which must be called with a \n  boolean argument once it has completed.\n* callback(result) - A callback which is called as soon as any iterator returns\n  true, or after all the iterator functions have finished. Result will be\n  either true or false depending on the values of the async tests.\n\n__Example__\n\n```js\nasync.some(['file1','file2','file3'], fs.exists, function(result){\n    // if result is true then at least one of the files exists\n});\n```\n\n---------------------------------------\n\n<a name=\"every\" />\n### every(arr, iterator, callback)\n\n__Alias:__ all\n\nReturns true if every element in the array satisfies an async test.\n_The callback for each iterator call only accepts a single argument of true or\nfalse, it does not accept an error argument first!_ This is in-line with the\nway node libraries work with truth tests like fs.exists.\n\n__Arguments__\n\n* arr - An array to iterate over.\n* iterator(item, callback) - A truth test to apply to each item in the array.\n  The iterator is passed a callback(truthValue) which must be called with a \n  boolean argument once it has completed.\n* callback(result) - A callback which is called after all the iterator\n  functions have finished. Result will be either true or false depending on\n  the values of the async tests.\n\n__Example__\n\n```js\nasync.every(['file1','file2','file3'], fs.exists, function(result){\n    // if result is true then every file exists\n});\n```\n\n---------------------------------------\n\n<a name=\"concat\" />\n### concat(arr, iterator, callback)\n\nApplies an iterator to each item in a list, concatenating the results. Returns the\nconcatenated list. The iterators are called in parallel, and the results are\nconcatenated as they return. There is no guarantee that the results array will\nbe returned in the original order of the arguments passed to the iterator function.\n\n__Arguments__\n\n* arr - An array to iterate over\n* iterator(item, callback) - A function to apply to each item in the array.\n  The iterator is passed a callback(err, results) which must be called once it \n  has completed with an error (which can be null) and an array of results.\n* callback(err, results) - A callback which is called after all the iterator\n  functions have finished, or an error has occurred. Results is an array containing\n  the concatenated results of the iterator function.\n\n__Example__\n\n```js\nasync.concat(['dir1','dir2','dir3'], fs.readdir, function(err, files){\n    // files is now a list of filenames that exist in the 3 directories\n});\n```\n\n---------------------------------------\n\n<a name=\"concatSeries\" />\n### concatSeries(arr, iterator, callback)\n\nSame as async.concat, but executes in series instead of parallel.\n\n\n## Control Flow\n\n<a name=\"series\" />\n### series(tasks, [callback])\n\nRun an array of functions in series, each one running once the previous\nfunction has completed. If any functions in the series pass an error to its\ncallback, no more functions are run and the callback for the series is\nimmediately called with the value of the error. Once the tasks have completed,\nthe results are passed to the final callback as an array.\n\nIt is also possible to use an object instead of an array. Each property will be\nrun as a function and the results will be passed to the final callback as an object\ninstead of an array. This can be a more readable way of handling results from\nasync.series.\n\n\n__Arguments__\n\n* tasks - An array or object containing functions to run, each function is passed\n  a callback(err, result) it must call on completion with an error (which can\n  be null) and an optional result value.\n* callback(err, results) - An optional callback to run once all the functions\n  have completed. This function gets a results array (or object) containing all \n  the result arguments passed to the task callbacks.\n\n__Example__\n\n```js\nasync.series([\n    function(callback){\n        // do some stuff ...\n        callback(null, 'one');\n    },\n    function(callback){\n        // do some more stuff ...\n        callback(null, 'two');\n    }\n],\n// optional callback\nfunction(err, results){\n    // results is now equal to ['one', 'two']\n});\n\n\n// an example using an object instead of an array\nasync.series({\n    one: function(callback){\n        setTimeout(function(){\n            callback(null, 1);\n        }, 200);\n    },\n    two: function(callback){\n        setTimeout(function(){\n            callback(null, 2);\n        }, 100);\n    }\n},\nfunction(err, results) {\n    // results is now equal to: {one: 1, two: 2}\n});\n```\n\n---------------------------------------\n\n<a name=\"parallel\" />\n### parallel(tasks, [callback])\n\nRun an array of functions in parallel, without waiting until the previous\nfunction has completed. If any of the functions pass an error to its\ncallback, the main callback is immediately called with the value of the error.\nOnce the tasks have completed, the results are passed to the final callback as an\narray.\n\nIt is also possible to use an object instead of an array. Each property will be\nrun as a function and the results will be passed to the final callback as an object\ninstead of an array. This can be a more readable way of handling results from\nasync.parallel.\n\n\n__Arguments__\n\n* tasks - An array or object containing functions to run, each function is passed \n  a callback(err, result) it must call on completion with an error (which can\n  be null) and an optional result value.\n* callback(err, results) - An optional callback to run once all the functions\n  have completed. This function gets a results array (or object) containing all \n  the result arguments passed to the task callbacks.\n\n__Example__\n\n```js\nasync.parallel([\n    function(callback){\n        setTimeout(function(){\n            callback(null, 'one');\n        }, 200);\n    },\n    function(callback){\n        setTimeout(function(){\n            callback(null, 'two');\n        }, 100);\n    }\n],\n// optional callback\nfunction(err, results){\n    // the results array will equal ['one','two'] even though\n    // the second function had a shorter timeout.\n});\n\n\n// an example using an object instead of an array\nasync.parallel({\n    one: function(callback){\n        setTimeout(function(){\n            callback(null, 1);\n        }, 200);\n    },\n    two: function(callback){\n        setTimeout(function(){\n            callback(null, 2);\n        }, 100);\n    }\n},\nfunction(err, results) {\n    // results is now equals to: {one: 1, two: 2}\n});\n```\n\n---------------------------------------\n\n<a name=\"parallel\" />\n### parallelLimit(tasks, limit, [callback])\n\nThe same as parallel only the tasks are executed in parallel with a maximum of \"limit\" \ntasks executing at any time.\n\nNote that the tasks are not executed in batches, so there is no guarantee that \nthe first \"limit\" tasks will complete before any others are started.\n\n__Arguments__\n\n* tasks - An array or object containing functions to run, each function is passed \n  a callback(err, result) it must call on completion with an error (which can\n  be null) and an optional result value.\n* limit - The maximum number of tasks to run at any time.\n* callback(err, results) - An optional callback to run once all the functions\n  have completed. This function gets a results array (or object) containing all \n  the result arguments passed to the task callbacks.\n\n---------------------------------------\n\n<a name=\"whilst\" />\n### whilst(test, fn, callback)\n\nRepeatedly call fn, while test returns true. Calls the callback when stopped,\nor an error occurs.\n\n__Arguments__\n\n* test() - synchronous truth test to perform before each execution of fn.\n* fn(callback) - A function to call each time the test passes. The function is\n  passed a callback(err) which must be called once it has completed with an \n  optional error argument.\n* callback(err) - A callback which is called after the test fails and repeated\n  execution of fn has stopped.\n\n__Example__\n\n```js\nvar count = 0;\n\nasync.whilst(\n    function () { return count < 5; },\n    function (callback) {\n        count++;\n        setTimeout(callback, 1000);\n    },\n    function (err) {\n        // 5 seconds have passed\n    }\n);\n```\n\n---------------------------------------\n\n<a name=\"doWhilst\" />\n### doWhilst(fn, test, callback)\n\nThe post check version of whilst. To reflect the difference in the order of operations `test` and `fn` arguments are switched. `doWhilst` is to `whilst` as `do while` is to `while` in plain JavaScript.\n\n---------------------------------------\n\n<a name=\"until\" />\n### until(test, fn, callback)\n\nRepeatedly call fn, until test returns true. Calls the callback when stopped,\nor an error occurs.\n\nThe inverse of async.whilst.\n\n---------------------------------------\n\n<a name=\"doUntil\" />\n### doUntil(fn, test, callback)\n\nLike doWhilst except the test is inverted. Note the argument ordering differs from `until`.\n\n---------------------------------------\n\n<a name=\"forever\" />\n### forever(fn, callback)\n\nCalls the asynchronous function 'fn' repeatedly, in series, indefinitely.\nIf an error is passed to fn's callback then 'callback' is called with the\nerror, otherwise it will never be called.\n\n---------------------------------------\n\n<a name=\"waterfall\" />\n### waterfall(tasks, [callback])\n\nRuns an array of functions in series, each passing their results to the next in\nthe array. However, if any of the functions pass an error to the callback, the\nnext function is not executed and the main callback is immediately called with\nthe error.\n\n__Arguments__\n\n* tasks - An array of functions to run, each function is passed a \n  callback(err, result1, result2, ...) it must call on completion. The first\n  argument is an error (which can be null) and any further arguments will be \n  passed as arguments in order to the next task.\n* callback(err, [results]) - An optional callback to run once all the functions\n  have completed. This will be passed the results of the last task's callback.\n\n\n\n__Example__\n\n```js\nasync.waterfall([\n    function(callback){\n        callback(null, 'one', 'two');\n    },\n    function(arg1, arg2, callback){\n        callback(null, 'three');\n    },\n    function(arg1, callback){\n        // arg1 now equals 'three'\n        callback(null, 'done');\n    }\n], function (err, result) {\n   // result now equals 'done'    \n});\n```\n\n---------------------------------------\n<a name=\"compose\" />\n### compose(fn1, fn2...)\n\nCreates a function which is a composition of the passed asynchronous\nfunctions. Each function consumes the return value of the function that\nfollows. Composing functions f(), g() and h() would produce the result of\nf(g(h())), only this version uses callbacks to obtain the return values.\n\nEach function is executed with the `this` binding of the composed function.\n\n__Arguments__\n\n* functions... - the asynchronous functions to compose\n\n\n__Example__\n\n```js\nfunction add1(n, callback) {\n    setTimeout(function () {\n        callback(null, n + 1);\n    }, 10);\n}\n\nfunction mul3(n, callback) {\n    setTimeout(function () {\n        callback(null, n * 3);\n    }, 10);\n}\n\nvar add1mul3 = async.compose(mul3, add1);\n\nadd1mul3(4, function (err, result) {\n   // result now equals 15\n});\n```\n\n---------------------------------------\n<a name=\"applyEach\" />\n### applyEach(fns, args..., callback)\n\nApplies the provided arguments to each function in the array, calling the\ncallback after all functions have completed. If you only provide the first\nargument then it will return a function which lets you pass in the\narguments as if it were a single function call.\n\n__Arguments__\n\n* fns - the asynchronous functions to all call with the same arguments\n* args... - any number of separate arguments to pass to the function\n* callback - the final argument should be the callback, called when all\n  functions have completed processing\n\n\n__Example__\n\n```js\nasync.applyEach([enableSearch, updateSchema], 'bucket', callback);\n\n// partial application example:\nasync.each(\n    buckets,\n    async.applyEach([enableSearch, updateSchema]),\n    callback\n);\n```\n\n---------------------------------------\n\n<a name=\"applyEachSeries\" />\n### applyEachSeries(arr, iterator, callback)\n\nThe same as applyEach only the functions are applied in series.\n\n---------------------------------------\n\n<a name=\"queue\" />\n### queue(worker, concurrency)\n\nCreates a queue object with the specified concurrency. Tasks added to the\nqueue will be processed in parallel (up to the concurrency limit). If all\nworkers are in progress, the task is queued until one is available. Once\na worker has completed a task, the task's callback is called.\n\n__Arguments__\n\n* worker(task, callback) - An asynchronous function for processing a queued\n  task, which must call its callback(err) argument when finished, with an \n  optional error as an argument.\n* concurrency - An integer for determining how many worker functions should be\n  run in parallel.\n\n__Queue objects__\n\nThe queue object returned by this function has the following properties and\nmethods:\n\n* length() - a function returning the number of items waiting to be processed.\n* concurrency - an integer for determining how many worker functions should be\n  run in parallel. This property can be changed after a queue is created to\n  alter the concurrency on-the-fly.\n* push(task, [callback]) - add a new task to the queue, the callback is called\n  once the worker has finished processing the task.\n  instead of a single task, an array of tasks can be submitted. the respective callback is used for every task in the list.\n* unshift(task, [callback]) - add a new task to the front of the queue.\n* saturated - a callback that is called when the queue length hits the concurrency and further tasks will be queued\n* empty - a callback that is called when the last item from the queue is given to a worker\n* drain - a callback that is called when the last item from the queue has returned from the worker\n\n__Example__\n\n```js\n// create a queue object with concurrency 2\n\nvar q = async.queue(function (task, callback) {\n    console.log('hello ' + task.name);\n    callback();\n}, 2);\n\n\n// assign a callback\nq.drain = function() {\n    console.log('all items have been processed');\n}\n\n// add some items to the queue\n\nq.push({name: 'foo'}, function (err) {\n    console.log('finished processing foo');\n});\nq.push({name: 'bar'}, function (err) {\n    console.log('finished processing bar');\n});\n\n// add some items to the queue (batch-wise)\n\nq.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function (err) {\n    console.log('finished processing bar');\n});\n\n// add some items to the front of the queue\n\nq.unshift({name: 'bar'}, function (err) {\n    console.log('finished processing bar');\n});\n```\n\n---------------------------------------\n\n<a name=\"cargo\" />\n### cargo(worker, [payload])\n\nCreates a cargo object with the specified payload. Tasks added to the\ncargo will be processed altogether (up to the payload limit). If the\nworker is in progress, the task is queued until it is available. Once\nthe worker has completed some tasks, each callback of those tasks is called.\n\n__Arguments__\n\n* worker(tasks, callback) - An asynchronous function for processing an array of\n  queued tasks, which must call its callback(err) argument when finished, with \n  an optional error as an argument.\n* payload - An optional integer for determining how many tasks should be\n  processed per round; if omitted, the default is unlimited.\n\n__Cargo objects__\n\nThe cargo object returned by this function has the following properties and\nmethods:\n\n* length() - a function returning the number of items waiting to be processed.\n* payload - an integer for determining how many tasks should be\n  process per round. This property can be changed after a cargo is created to\n  alter the payload on-the-fly.\n* push(task, [callback]) - add a new task to the queue, the callback is called\n  once the worker has finished processing the task.\n  instead of a single task, an array of tasks can be submitted. the respective callback is used for every task in the list.\n* saturated - a callback that is called when the queue length hits the concurrency and further tasks will be queued\n* empty - a callback that is called when the last item from the queue is given to a worker\n* drain - a callback that is called when the last item from the queue has returned from the worker\n\n__Example__\n\n```js\n// create a cargo object with payload 2\n\nvar cargo = async.cargo(function (tasks, callback) {\n    for(var i=0; i<tasks.length; i++){\n      console.log('hello ' + tasks[i].name);\n    }\n    callback();\n}, 2);\n\n\n// add some items\n\ncargo.push({name: 'foo'}, function (err) {\n    console.log('finished processing foo');\n});\ncargo.push({name: 'bar'}, function (err) {\n    console.log('finished processing bar');\n});\ncargo.push({name: 'baz'}, function (err) {\n    console.log('finished processing baz');\n});\n```\n\n---------------------------------------\n\n<a name=\"auto\" />\n### auto(tasks, [callback])\n\nDetermines the best order for running functions based on their requirements.\nEach function can optionally depend on other functions being completed first,\nand each function is run as soon as its requirements are satisfied. If any of\nthe functions pass an error to their callback, that function will not complete\n(so any other functions depending on it will not run) and the main callback\nwill be called immediately with the error. Functions also receive an object\ncontaining the results of functions which have completed so far.\n\nNote, all functions are called with a results object as a second argument, \nso it is unsafe to pass functions in the tasks object which cannot handle the\nextra argument. For example, this snippet of code:\n\n```js\nasync.auto({\n  readData: async.apply(fs.readFile, 'data.txt', 'utf-8')\n}, callback);\n```\n\nwill have the effect of calling readFile with the results object as the last\nargument, which will fail:\n\n```js\nfs.readFile('data.txt', 'utf-8', cb, {});\n```\n\nInstead, wrap the call to readFile in a function which does not forward the \nresults object:\n\n```js\nasync.auto({\n  readData: function(cb, results){\n    fs.readFile('data.txt', 'utf-8', cb);\n  }\n}, callback);\n```\n\n__Arguments__\n\n* tasks - An object literal containing named functions or an array of\n  requirements, with the function itself the last item in the array. The key\n  used for each function or array is used when specifying requirements. The \n  function receives two arguments: (1) a callback(err, result) which must be \n  called when finished, passing an error (which can be null) and the result of \n  the function's execution, and (2) a results object, containing the results of\n  the previously executed functions.\n* callback(err, results) - An optional callback which is called when all the\n  tasks have been completed. The callback will receive an error as an argument\n  if any tasks pass an error to their callback. Results will always be passed\n\tbut if an error occurred, no other tasks will be performed, and the results\n\tobject will only contain partial results.\n  \n\n__Example__\n\n```js\nasync.auto({\n    get_data: function(callback){\n        // async code to get some data\n    },\n    make_folder: function(callback){\n        // async code to create a directory to store a file in\n        // this is run at the same time as getting the data\n    },\n    write_file: ['get_data', 'make_folder', function(callback){\n        // once there is some data and the directory exists,\n        // write the data to a file in the directory\n        callback(null, filename);\n    }],\n    email_link: ['write_file', function(callback, results){\n        // once the file is written let's email a link to it...\n        // results.write_file contains the filename returned by write_file.\n    }]\n});\n```\n\nThis is a fairly trivial example, but to do this using the basic parallel and\nseries functions would look like this:\n\n```js\nasync.parallel([\n    function(callback){\n        // async code to get some data\n    },\n    function(callback){\n        // async code to create a directory to store a file in\n        // this is run at the same time as getting the data\n    }\n],\nfunction(err, results){\n    async.series([\n        function(callback){\n            // once there is some data and the directory exists,\n            // write the data to a file in the directory\n        },\n        function(callback){\n            // once the file is written let's email a link to it...\n        }\n    ]);\n});\n```\n\nFor a complicated series of async tasks using the auto function makes adding\nnew tasks much easier and makes the code more readable.\n\n\n---------------------------------------\n\n<a name=\"iterator\" />\n### iterator(tasks)\n\nCreates an iterator function which calls the next function in the array,\nreturning a continuation to call the next one after that. It's also possible to\n'peek' the next iterator by doing iterator.next().\n\nThis function is used internally by the async module but can be useful when\nyou want to manually control the flow of functions in series.\n\n__Arguments__\n\n* tasks - An array of functions to run.\n\n__Example__\n\n```js\nvar iterator = async.iterator([\n    function(){ sys.p('one'); },\n    function(){ sys.p('two'); },\n    function(){ sys.p('three'); }\n]);\n\nnode> var iterator2 = iterator();\n'one'\nnode> var iterator3 = iterator2();\n'two'\nnode> iterator3();\n'three'\nnode> var nextfn = iterator2.next();\nnode> nextfn();\n'three'\n```\n\n---------------------------------------\n\n<a name=\"apply\" />\n### apply(function, arguments..)\n\nCreates a continuation function with some arguments already applied, a useful\nshorthand when combined with other control flow functions. Any arguments\npassed to the returned function are added to the arguments originally passed\nto apply.\n\n__Arguments__\n\n* function - The function you want to eventually apply all arguments to.\n* arguments... - Any number of arguments to automatically apply when the\n  continuation is called.\n\n__Example__\n\n```js\n// using apply\n\nasync.parallel([\n    async.apply(fs.writeFile, 'testfile1', 'test1'),\n    async.apply(fs.writeFile, 'testfile2', 'test2'),\n]);\n\n\n// the same process without using apply\n\nasync.parallel([\n    function(callback){\n        fs.writeFile('testfile1', 'test1', callback);\n    },\n    function(callback){\n        fs.writeFile('testfile2', 'test2', callback);\n    }\n]);\n```\n\nIt's possible to pass any number of additional arguments when calling the\ncontinuation:\n\n```js\nnode> var fn = async.apply(sys.puts, 'one');\nnode> fn('two', 'three');\none\ntwo\nthree\n```\n\n---------------------------------------\n\n<a name=\"nextTick\" />\n### nextTick(callback)\n\nCalls the callback on a later loop around the event loop. In node.js this just\ncalls process.nextTick, in the browser it falls back to setImmediate(callback)\nif available, otherwise setTimeout(callback, 0), which means other higher priority\nevents may precede the execution of the callback.\n\nThis is used internally for browser-compatibility purposes.\n\n__Arguments__\n\n* callback - The function to call on a later loop around the event loop.\n\n__Example__\n\n```js\nvar call_order = [];\nasync.nextTick(function(){\n    call_order.push('two');\n    // call_order now equals ['one','two']\n});\ncall_order.push('one')\n```\n\n<a name=\"times\" />\n### times(n, callback)\n\nCalls the callback n times and accumulates results in the same manner\nyou would use with async.map.\n\n__Arguments__\n\n* n - The number of times to run the function.\n* callback - The function to call n times.\n\n__Example__\n\n```js\n// Pretend this is some complicated async factory\nvar createUser = function(id, callback) {\n  callback(null, {\n    id: 'user' + id\n  })\n}\n// generate 5 users\nasync.times(5, function(n, next){\n    createUser(n, function(err, user) {\n      next(err, user)\n    })\n}, function(err, users) {\n  // we should now have 5 users\n});\n```\n\n<a name=\"timesSeries\" />\n### timesSeries(n, callback)\n\nThe same as times only the iterator is applied to each item in the array in\nseries. The next iterator is only called once the current one has completed\nprocessing. The results array will be in the same order as the original.\n\n\n## Utils\n\n<a name=\"memoize\" />\n### memoize(fn, [hasher])\n\nCaches the results of an async function. When creating a hash to store function\nresults against, the callback is omitted from the hash and an optional hash\nfunction can be used.\n\nThe cache of results is exposed as the `memo` property of the function returned\nby `memoize`.\n\n__Arguments__\n\n* fn - the function you to proxy and cache results from.\n* hasher - an optional function for generating a custom hash for storing\n  results, it has all the arguments applied to it apart from the callback, and\n  must be synchronous.\n\n__Example__\n\n```js\nvar slow_fn = function (name, callback) {\n    // do something\n    callback(null, result);\n};\nvar fn = async.memoize(slow_fn);\n\n// fn can now be used as if it were slow_fn\nfn('some name', function () {\n    // callback\n});\n```\n\n<a name=\"unmemoize\" />\n### unmemoize(fn)\n\nUndoes a memoized function, reverting it to the original, unmemoized\nform. Comes handy in tests.\n\n__Arguments__\n\n* fn - the memoized function\n\n<a name=\"log\" />\n### log(function, arguments)\n\nLogs the result of an async function to the console. Only works in node.js or\nin browsers that support console.log and console.error (such as FF and Chrome).\nIf multiple arguments are returned from the async function, console.log is\ncalled on each argument in order.\n\n__Arguments__\n\n* function - The function you want to eventually apply all arguments to.\n* arguments... - Any number of arguments to apply to the function.\n\n__Example__\n\n```js\nvar hello = function(name, callback){\n    setTimeout(function(){\n        callback(null, 'hello ' + name);\n    }, 1000);\n};\n```\n```js\nnode> async.log(hello, 'world');\n'hello world'\n```\n\n---------------------------------------\n\n<a name=\"dir\" />\n### dir(function, arguments)\n\nLogs the result of an async function to the console using console.dir to\ndisplay the properties of the resulting object. Only works in node.js or\nin browsers that support console.dir and console.error (such as FF and Chrome).\nIf multiple arguments are returned from the async function, console.dir is\ncalled on each argument in order.\n\n__Arguments__\n\n* function - The function you want to eventually apply all arguments to.\n* arguments... - Any number of arguments to apply to the function.\n\n__Example__\n\n```js\nvar hello = function(name, callback){\n    setTimeout(function(){\n        callback(null, {hello: name});\n    }, 1000);\n};\n```\n```js\nnode> async.dir(hello, 'world');\n{hello: 'world'}\n```\n\n---------------------------------------\n\n<a name=\"noConflict\" />\n### noConflict()\n\nChanges the value of async back to its original value, returning a reference to the\nasync object.\n",
    3939  "readmeFilename": "README.md",
    4040  "homepage": "https://github.com/caolan/async",
    41   "_id": "async@0.2.9",
     41  "_id": "async@0.2.10",
    4242  "_from": "async@~0.2.7"
    4343}
  • Dev/trunk/src/node_modules/request/node_modules/form-data/package.json

    r484 r489  
    3737  "homepage": "https://github.com/felixge/node-form-data",
    3838  "_id": "form-data@0.0.8",
    39   "_from": "form-data@0.0.8"
     39  "dist": {
     40    "shasum": "ba68e7462ee0d17cd3c364fe2ba5ff72af5ae826"
     41  },
     42  "_from": "form-data@0.0.8",
     43  "_resolved": "https://registry.npmjs.org/form-data/-/form-data-0.0.8.tgz"
    4044}
  • Dev/trunk/src/node_modules/request/node_modules/http-signature/node_modules/asn1/package.json

    r484 r489  
    3131  "scripts": {
    3232    "pretest": "which gjslint; if [[ \"$?\" = 0 ]] ; then  gjslint --nojsdoc -r lib -r tst; else echo \"Missing gjslint. Skipping lint\"; fi",
    33     "test": "./node_modules/.bin/tap ./tst"
     33    "test": "tap ./tst"
    3434  },
    3535  "readme": "node-asn1 is a library for encoding and decoding ASN.1 datatypes in pure JS.\nCurrently BER encoding is supported; at some point I'll likely have to do DER.\n\n## Usage\n\nMostly, if you're *actually* needing to read and write ASN.1, you probably don't\nneed this readme to explain what and why.  If you have no idea what ASN.1 is,\nsee this: ftp://ftp.rsa.com/pub/pkcs/ascii/layman.asc\n\nThe source is pretty much self-explanatory, and has read/write methods for the\ncommon types out there.\n\n### Decoding\n\nThe following reads an ASN.1 sequence with a boolean.\n\n    var Ber = require('asn1').Ber;\n\n    var reader = new Ber.Reader(new Buffer([0x30, 0x03, 0x01, 0x01, 0xff]));\n\n    reader.readSequence();\n    console.log('Sequence len: ' + reader.length);\n    if (reader.peek() === Ber.Boolean)\n      console.log(reader.readBoolean());\n\n### Encoding\n\nThe following generates the same payload as above.\n\n    var Ber = require('asn1').Ber;\n\n    var writer = new Ber.Writer();\n\n    writer.startSequence();\n    writer.writeBoolean(true);\n    writer.endSequence();\n\n    console.log(writer.buffer);\n\n## Installation\n\n    npm install asn1\n\n## License\n\nMIT.\n\n## Bugs\n\nSee <https://github.com/mcavage/node-asn1/issues>.\n",
  • Dev/trunk/src/node_modules/request/node_modules/http-signature/package.json

    r484 r489  
    1515  "main": "lib/index.js",
    1616  "scripts": {
    17     "test": "./node_modules/.bin/tap tst/*.js"
     17    "test": "tap tst/*.js"
    1818  },
    1919  "dependencies": {
  • Dev/trunk/src/node_modules/request/node_modules/qs/index.js

    r484 r489  
    3838var objectKeys = Object.keys || function(obj) {
    3939  var ret = [];
    40   for (var key in obj) ret.push(key);
     40  for (var key in obj) {
     41    if (obj.hasOwnProperty(key)) {
     42      ret.push(key);
     43    }
     44  }
    4145  return ret;
    4246};
     
    6468
    6569/**
    66  * Create a nullary object if possible
    67  */
    68 
    69 function createObject() {
    70   return Object.create
    71     ? Object.create(null)
    72     : {};
    73 }
    74 
    75 /**
    7670 * Cache non-integer test regexp.
    7771 */
     
    8074
    8175function promote(parent, key) {
    82   if (parent[key].length == 0) return parent[key] = createObject();
    83   var t = createObject();
     76  if (parent[key].length == 0) return parent[key] = {}
     77  var t = {};
    8478  for (var i in parent[key]) {
    8579    if (hasOwnProperty.call(parent[key], i)) {
     
    9387function parse(parts, parent, key, val) {
    9488  var part = parts.shift();
     89 
     90  // illegal
     91  if (Object.getOwnPropertyDescriptor(Object.prototype, key)) return;
     92 
    9593  // end
    9694  if (!part) {
     
    141139  } else {
    142140    if (!isint.test(key) && isArray(parent.base)) {
    143       var t = createObject();
     141      var t = {};
    144142      for (var k in parent.base) t[k] = parent.base[k];
    145143      parent.base = t;
     
    174172  }
    175173
    176   return obj;
    177 }
    178 
    179 /**
    180  * Restore Object.prototype.
    181  * see pull-request #58
    182  */
    183 
    184 function restoreProto(obj) {
    185   if (!Object.create) return obj;
    186   if (isArray(obj)) return obj;
    187   if (obj && 'object' != typeof obj) return obj;
    188 
    189   for (var key in obj) {
    190     if (hasOwnProperty.call(obj, key)) {
    191       obj[key] = restoreProto(obj[key]);
    192     }
    193   }
    194 
    195   obj.__proto__ = Object.prototype;
    196174  return obj;
    197175}
     
    228206
    229207    return merge(ret, decode(key), decode(val));
    230   }, { base: createObject() }).base;
    231 
    232   return restoreProto(compact(ret));
     208  }, { base: {} }).base;
     209
     210  return compact(ret);
    233211}
    234212
     
    342320function set(obj, key, val) {
    343321  var v = obj[key];
     322  if (Object.getOwnPropertyDescriptor(Object.prototype, key)) return;
    344323  if (undefined === v) {
    345324    obj[key] = val;
  • Dev/trunk/src/node_modules/request/node_modules/qs/package.json

    r484 r489  
    22  "name": "qs",
    33  "description": "querystring parser",
    4   "version": "0.6.5",
     4  "version": "0.6.6",
    55  "keywords": [
    66    "query string",
     
    3434  },
    3535  "homepage": "https://github.com/visionmedia/node-querystring",
    36   "_id": "qs@0.6.5",
     36  "_id": "qs@0.6.6",
    3737  "_from": "qs@~0.6.0"
    3838}
  • Dev/trunk/src/node_modules/request/package.json

    r484 r489  
    4545  "homepage": "https://github.com/mikeal/request",
    4646  "_id": "request@2.21.0",
    47   "_from": "request@2.21.0"
     47  "dist": {
     48    "shasum": "bbbeba797a81249001ec7b8af8a1d0350d2b6fc6"
     49  },
     50  "_from": "request@2.21.0",
     51  "_resolved": "https://registry.npmjs.org/request/-/request-2.21.0.tgz"
    4852}
  • Dev/trunk/src/node_modules/underscore/package.json

    r484 r489  
    3232  },
    3333  "_id": "underscore@1.4.4",
    34   "_from": "underscore@"
     34  "dist": {
     35    "shasum": "3e7ceb21f205bc19964685e1fdd52c8f77773674"
     36  },
     37  "_from": "underscore@1.4.4",
     38  "_resolved": "https://registry.npmjs.org/underscore/-/underscore-1.4.4.tgz"
    3539}
  • Dev/trunk/src/node_modules/ya-csv/README.md

    r484 r489  
    1717    npm install ya-csv
    1818
    19 Current version requires at least Node.js v0.2.3 and it's tested with Node.js v0.4.12, 0.6.11 and 0.7.5. Hope it works with the other versions in between too.
     19Current version requires at least Node.js v0.2.3 and it's tested with Node.js v0.4.12, 0.6.11, 0.7.5 and v0.10.24. Hope it works with the other versions in between too.
    2020
    2121## Features
  • Dev/trunk/src/node_modules/ya-csv/bin/reshuffle.js

    r484 r489  
    11var csv = require('../lib/ya-csv'),
    2     sys = require('sys');
     2    util = require('util');
    33
    44var reader = csv.createCsvStreamReader(process.openStdin(), { columnsFromHeader: true });
     
    66
    77if (process.argv.length < 3) {
    8     sys.error("Usage: " + process.argv[0] + " " + process.argv[1] + " <output columns>");
     8    util.error("Usage: " + process.argv[0] + " " + process.argv[1] + " <output columns>");
    99    process.exit(1);
    1010}
  • Dev/trunk/src/node_modules/ya-csv/lib/ya-csv.js

    r484 r489  
    7373         * @return {ReadStream} the readstream instance
    7474         */
    75         self.destoy = function(){
     75        self.destroy = function(){
    7676            readStream.destroy();
    7777            return self;
     
    113113                var isEscape = false;
    114114                if (c === this.escapechar) {
    115                     var nextChar = data.charAt(i + 1);
    116                     if (this._isEscapable(nextChar)) {
    117                         this._addCharacter(nextChar);
    118                         i++;
    119                         isEscape = true;
     115                    // double-quote at the field beginning does not count as an escape string`
     116                    if (c !== this.quotechar || ps.openField || ps.quotedField) {
     117                       var nextChar = data.charAt(i + 1);
     118                       if (this._isEscapable(nextChar)) {
     119                           this._addCharacter(nextChar);
     120                           i++;
     121                           isEscape = true;
     122                        }
    120123                    }
    121124                }
     
    217220    var ps = this.parsingStatus;
    218221    if (this.columnsFromHeader && ps.rows === 0) {
    219         this.setColumnNames(ps.openRecord);
     222        // user has passed columnNames through option
     223        if (this.columnNames.length === 0)
     224          this.setColumnNames(ps.openRecord);
    220225    } else if (this.columnNames != null && this.columnNames.length > 0) {
    221226        var objResult = {};
     
    327332function _setOptions(obj, options) {
    328333    options = options || {};
    329     obj.separator   = options.separator   || ',';
    330     obj.quotechar   = options.quote       || '"';
    331     obj.escapechar  = options.escape      || '"';
    332     obj.commentchar = options.comment     || '';
    333     obj.columnNames = options.columnNames || [];
    334     obj.columnsFromHeader = options.columnsFromHeader || false;
    335     obj.nestedQuotes = options.nestedQuotes || false;
    336 };
     334    obj.separator = (typeof options.separator !== 'undefined') ? options.separator : ',';
     335    obj.quotechar = (typeof options.quote !== 'undefined') ? options.quote : '"';
     336    obj.escapechar = (typeof options.escape !== 'undefined') ? options.escape : '"';
     337    obj.commentchar = (typeof options.comment !== 'undefined') ? options.comment : '';
     338    obj.columnNames = (typeof options.columnNames !== 'undefined') ? options.columnNames : [];
     339    obj.columnsFromHeader = (typeof options.columnsFromHeader !== 'undefined') ? options.columnsFromHeader : false;
     340    obj.nestedQuotes = (typeof options.nestedQuotes !== 'undefined') ? options.nestedQuotes : false;
     341};
  • Dev/trunk/src/node_modules/ya-csv/package.json

    r484 r489  
    22  "name": "ya-csv",
    33  "description": "CSV parser and generator for Node.js",
    4   "version": "0.9.2",
     4  "version": "0.9.3",
    55  "keywords": [
    66    "node",
     
    3737  },
    3838  "main": "lib/ya-csv",
    39   "readme": "# ya-csv\n\nEvent based CSV parser and writer for Node.js suitable for processing large CSV streams.\n\n    // A simple echo program:\n    var csv = require('ya-csv');\n\n    var reader = csv.createCsvStreamReader(process.openStdin());\n    var writer = csv.createCsvStreamWriter(process.stdout);\n\n    reader.addListener('data', function(data) {\n        writer.writeRecord(data);\n    });\n\n## Installation\n\n    npm install ya-csv\n\nCurrent version requires at least Node.js v0.2.3 and it's tested with Node.js v0.4.12, 0.6.11 and 0.7.5. Hope it works with the other versions in between too.\n\n## Features\n\n - event based, suitable for processing big CSV streams\n - configurable separator, quote and escape characters (comma, double-quote and double-quote by default)\n - ignores lines starting with configurable comment character (off by default)\n - supports memory-only streaming\n\n## More examples\n\nEcho first column of the `data.csv` file:\n\n    // equivalent of csv.createCsvFileReader('data.csv') \n    var reader = csv.createCsvFileReader('data.csv', {\n        'separator': ',',\n        'quote': '\"',\n        'escape': '\"',       \n        'comment': '',\n    });\n    var writer = new csv.CsvWriter(process.stdout);\n    reader.addListener('data', function(data) {\n        writer.writeRecord([ data[0] ]);\n    });\n\nReturn data in objects rather than arrays: either by grabbing the column names form the header row (first row is not passed to the `data` listener):\n\n    var reader = csv.createCsvFileReader('data.csv', { columnsFromHeader: true });\n    reader.addListener('data', function(data) {\n        // supposing there are so named columns in the source file\n        sys.puts(data.col1 + \" ... \" + data.col2);\n    });\n\n... or by providing column names from the client code (first row is passed to the `data` listener in this case):\n\n    var reader = csv.createCsvFileReader('data.csv');\n    reader.setColumnNames([ 'col1', 'col2' ]);\n    reader.addListener('data', function(data) {\n        sys.puts(data.col1 + \" ... \" + data.col2);\n    });\n\nNote `reader.setColumnNames()` resets the column names so next invocation of the `data` listener will again receive the data in an array rather than an object.\n\nConvert the `/etc/passwd` file to comma separated format, drop commented lines and dump the results to the standard output:\n\n    var reader = csv.createCsvFileReader('/etc/passwd', {\n        'separator': ':',\n        'quote': '\"',\n        'escape': '\"',\n        'comment': '#',\n    });\n    var writer = new csv.CsvWriter(process.stdout);\n    reader.addListener('data', function(data) {\n        writer.writeRecord(data);\n    });\n\nParsing an upload as the data comes in, using node-formidable:\n\n    upload_form.onPart = function(part) {\n        if (!part.filename) { upload_form.handlePart(part); return }\n\n        var reader = csv.createCsvFileReader({'comment': '#'});\n        reader.addListener('data', function(data) {\n            saveRecord(data);\n        });\n\n        part.on('data', function(buffer) {\n            // Pipe incoming data into the reader.\n            reader.parse(buffer);\n        });\n        part.on('end', function() {\n            reader.end()\n        }\n    }\n",
     39  "readme": "# ya-csv\n\nEvent based CSV parser and writer for Node.js suitable for processing large CSV streams.\n\n    // A simple echo program:\n    var csv = require('ya-csv');\n\n    var reader = csv.createCsvStreamReader(process.openStdin());\n    var writer = csv.createCsvStreamWriter(process.stdout);\n\n    reader.addListener('data', function(data) {\n        writer.writeRecord(data);\n    });\n\n## Installation\n\n    npm install ya-csv\n\nCurrent version requires at least Node.js v0.2.3 and it's tested with Node.js v0.4.12, 0.6.11, 0.7.5 and v0.10.24. Hope it works with the other versions in between too.\n\n## Features\n\n - event based, suitable for processing big CSV streams\n - configurable separator, quote and escape characters (comma, double-quote and double-quote by default)\n - ignores lines starting with configurable comment character (off by default)\n - supports memory-only streaming\n\n## More examples\n\nEcho first column of the `data.csv` file:\n\n    // equivalent of csv.createCsvFileReader('data.csv') \n    var reader = csv.createCsvFileReader('data.csv', {\n        'separator': ',',\n        'quote': '\"',\n        'escape': '\"',       \n        'comment': '',\n    });\n    var writer = new csv.CsvWriter(process.stdout);\n    reader.addListener('data', function(data) {\n        writer.writeRecord([ data[0] ]);\n    });\n\nReturn data in objects rather than arrays: either by grabbing the column names form the header row (first row is not passed to the `data` listener):\n\n    var reader = csv.createCsvFileReader('data.csv', { columnsFromHeader: true });\n    reader.addListener('data', function(data) {\n        // supposing there are so named columns in the source file\n        sys.puts(data.col1 + \" ... \" + data.col2);\n    });\n\n... or by providing column names from the client code (first row is passed to the `data` listener in this case):\n\n    var reader = csv.createCsvFileReader('data.csv');\n    reader.setColumnNames([ 'col1', 'col2' ]);\n    reader.addListener('data', function(data) {\n        sys.puts(data.col1 + \" ... \" + data.col2);\n    });\n\nNote `reader.setColumnNames()` resets the column names so next invocation of the `data` listener will again receive the data in an array rather than an object.\n\nConvert the `/etc/passwd` file to comma separated format, drop commented lines and dump the results to the standard output:\n\n    var reader = csv.createCsvFileReader('/etc/passwd', {\n        'separator': ':',\n        'quote': '\"',\n        'escape': '\"',\n        'comment': '#',\n    });\n    var writer = new csv.CsvWriter(process.stdout);\n    reader.addListener('data', function(data) {\n        writer.writeRecord(data);\n    });\n\nParsing an upload as the data comes in, using node-formidable:\n\n    upload_form.onPart = function(part) {\n        if (!part.filename) { upload_form.handlePart(part); return }\n\n        var reader = csv.createCsvFileReader({'comment': '#'});\n        reader.addListener('data', function(data) {\n            saveRecord(data);\n        });\n\n        part.on('data', function(buffer) {\n            // Pipe incoming data into the reader.\n            reader.parse(buffer);\n        });\n        part.on('end', function() {\n            reader.end()\n        }\n    }\n",
    4040  "readmeFilename": "README.md",
    41   "_id": "ya-csv@0.9.2",
     41  "homepage": "https://github.com/koles/ya-csv",
     42  "_id": "ya-csv@0.9.3",
    4243  "dist": {
    43     "shasum": "088ddf523ca066bbe654146100cf70030d9f6779"
     44    "shasum": "e3b1e84b699c569949b8b68a319a1b065ac456b3"
    4445  },
    45   "_from": "ya-csv@",
    46   "_resolved": "https://registry.npmjs.org/ya-csv/-/ya-csv-0.9.2.tgz"
     46  "_from": "ya-csv@0.9.3",
     47  "_resolved": "https://registry.npmjs.org/ya-csv/-/ya-csv-0.9.3.tgz"
    4748}
  • Dev/trunk/src/node_modules/ya-csv/test/echo.js

    r484 r489  
    11var csv  = require('../lib/ya-csv'),
    2     sys  = require('sys');
     2    util = require('util');
    33
    4 sys.debug('start');
     4util.debug('start');
    55
    66if (process.argv.length < 3) {
    7     sys.error("Usage: node " + process.argv[1] + " <csv file>");
     7    util.error("Usage: node " + process.argv[1] + " <csv file>");
    88    process.exit(1);
    99}
     
    2424
    2525csvIn.addListener('end', function() {
    26     sys.debug('end');
    27     sys.debug(columns + ' columns, ' + lines + ' lines');
     26    util.debug('end');
     27    util.debug(columns + ' columns, ' + lines + ' lines');
    2828});
    2929
  • Dev/trunk/src/node_modules/ya-csv/test/index.js

    r484 r489  
    1 var sys;
     1var util;
    22try {
    3   sys    = require('util');
     3  util    = require('util');
    44} catch (e) {
    5   sys    = require('sys');
     5  util = require('sys');
    66}
    77
     
    2727csvIn.addListener('end', function() {
    2828    assert.strictEqual(expectedRows, lines, "Wrong number of records");
    29     sys.debug(columns + ' columns, ' + lines + ' lines');
     29    util.debug(columns + ' columns, ' + lines + ' lines');
    3030});
    3131
  • Dev/trunk/src/node_modules/ya-csv/test/stream.js

    r484 r489  
    11var csv  = require('../lib/ya-csv'),
    2     sys  = require('sys'),
     2    util = require('util'),
    33    fs = require('fs');
    44
    5 sys.debug('start');
     5util.debug('start');
    66
    77if (process.argv.length < 3) {
    8     sys.error("Usage: node " + process.argv[1] + " <csv file>");
     8    util.error("Usage: node " + process.argv[1] + " <csv file>");
    99    process.exit(1);
    1010}
     
    2020
    2121csvIn.addListener('end', function() {
    22     sys.debug('end');
    23     sys.debug(columns + ' columns, ' + lines + ' lines');
     22    util.debug('end');
     23    util.debug(columns + ' columns, ' + lines + ' lines');
    2424});
    2525
    2626csvIn.addListener('error', function(e) {
    27     sys.debug('error');
    28     sys.debug(e);
     27    util.debug('error');
     28    util.debug(e);
    2929});
    3030
     
    3838fileIn.setEncoding('utf8');
    3939fileIn.on('data', function(data) {
    40   sys.debug(data);
     40  util.debug(data);
    4141  csvIn.parse(data);
    4242});
  • Dev/trunk/src/package.json

    r487 r489  
    66    "express": "~3.2.6",
    77    "underscore": "~1.4.4",
    8     "passport": "~0.1.17",
     8    "passport": "~0.1.18",
    99    "passport-local": "~0.1.6",
    10     "q": "~0.9.6",
     10    "q": "~0.9.7",
    1111    "request": "~2.21.0",
    12     "ya-csv": "~0.9.2",
     12    "ya-csv": "~0.9.3",
    1313    "tv4": "~1.0.16"
    1414  },
Note: See TracChangeset for help on using the changeset viewer.