{"name":"asyncblock-generators","version":"2.2.7","description":"asyncblock without the fibers","keywords":["fiber","fibers","coroutine","stop","go","green","red"],"license":"MIT","homepage":"https://github.com/scriby/asyncblock-generators","author":{"name":"Chris Scribner"},"main":"asyncblock","repository":{"type":"git","url":"git://github.com/scriby/asyncblock-generators.git"},"dependencies":{"esprima":"2.6.0"},"devDependencies":{"vows":"0.7.0","jshint":"0.5.9"},"engines":{"node":">= 4.0.0"},"gitHead":"a9f32cc0a4679d48f37218f4275d9cf14c4ebf28","bugs":{"url":"https://github.com/scriby/asyncblock-generators/issues"},"_id":"asyncblock-generators@2.2.7","scripts":{},"_shasum":"df5420389aa09ea4ef9eb346c7d2960ec57d66fc","_from":".","_npmVersion":"2.14.7","_nodeVersion":"4.2.3","_npmUser":{"name":"scriby","email":"scriby@gmail.com"},"dist":{"shasum":"df5420389aa09ea4ef9eb346c7d2960ec57d66fc","tarball":"http://registry-npm.ywwl.com/asyncblock-generators/download/asyncblock-generators-2.2.7.tgz","integrity":"sha512-My33fVjDkXt6AovDjun9y7Sk4ja9MjmSTs++qXm8P4mXKQsF8JoUaMiH7ZCi/tjOLIZp87pIhyFnsZlX8TePkA==","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCIAygeBgmSvpppkgIX79n/k8DBblDFmQZqooRc3CAvRxFAiB+IwEyFHyiOt2L4chKZiwwKhfYtpiUgzJAiWoXJuImWg=="}],"size":27106,"noattachment":false,"key":"/asyncblock-generators/-/asyncblock-generators-2.2.7.tgz"},"maintainers":[{"name":"scriby","email":"scriby@gmail.com"}],"directories":{},"readme":"```\n                                        ______  ______              ______  \n______ ______________  _________ __________  /_ ___  /______ __________  /__\n_  __ `/__  ___/__  / / /__  __ \\_  ___/__  __ \\__  / _  __ \\_  ___/__  //_/\n/ /_/ / _(__  ) _  /_/ / _  / / // /__  _  /_/ /_  /  / /_/ // /__  _  ,<   \n\\__,_/  /____/  _\\__, /  /_/ /_/ \\___/  /_.___/ /_/   \\____/ \\___/  /_/|_|  \n                /____/                                                      \n\n```\n==================================================================\n\nA synchronous-style flow control library built on top of harmony generators. This library started its life as [asyncblock](https://github.com/scriby/asyncblock),\nwhich was written on top of Fibers.\n\n###Installation\n\n```javascript\nnpm install asyncblock-generators\n```\n\n### Why should I use asyncblock?\n\n* Write async code in synchronous style without blocking the event loop\n* Effortlessly combine serial and parallel operations with minimal boilerplate\n* Produce code which is easier to read, reason about, and modify\n    * Compared to flow control libraries, asyncblock makes it easy to share data between async steps. There's no need to create variables in an outer scope or use \"waterfall\".\n* Simplify error handling practices\n    * If an error occurs in an async step, automatically call your callback with the error, or throw an Error\n* Improve debugging by not losing stack traces across async calls\n    * Line numbers don't change. What's in the stack trace maps directly to your code (You may lose this with CPS transforms)\n    * If using a debugger, it's easy to step line-by-line through asyncblock code (compared to async libraries)\n\n## Usage differences between this module and asyncblock\n\n* All functions passed to an asyncblock must be generator functions (look like function*(){})\n* Any time you are waiting on a value to resolve the \"yield\" keyword must be used\n* There is a new shorthand for waiting on one item: `var x = yield fs.readFile(path, 'utf8', flow.callback());`\n* When using source transformation, .defer() and .future() calls may only be yielded once. (This is probably fixable, but I haven't looked into it yet)\n* asyncblock.getCurrentFiber() is not availabe in this module (this is not commonly used)\n\nCheat sheet for when yield must be used:\n\n* `yield flow.wait();`\n* `yield flow.get('key');`\n* `yield flow.sync(setTimeout(flow.add(), 1000);`\n* `yield fs.readFile(path, 'utf8', flow.callback())`\n* `yield fs.readFile(path, 'utf8').sync()`\n* `var x = fs.readFile(path, 'utf8').defer(); console.log(yield x)`\n* `var x = fs.readFile(path, 'utf8').future(); console.log(yield x.result)`\n\nThis library is unable to detect it if you accidentally forget to include a yield keyword. Please pay close attention to including it when necessary.\n\n## Overview\n\nCheck out the [overview](https://github.com/scriby/asyncblock/blob/master/docs/overview.md) to get an at-a-glance overview\nof the different ways asyncblock can be used. Please note that the docs are for the fibers version of asyncblock, and the examples\nwill need to be translated to include * and yields for the generator version.\n\n## Examples\n\nA few quick examples to show off the functionality of asyncblock:\n\n### Sleeping in series\n\n```javascript\nvar ab = require('asyncblock-generators');\n\nab(function*(flow){\n    console.time('time');\n\n    setTimeout(flow.add(), 1000);\n    yield flow.wait(); //Wait for the first setTimeout to finish\n\n    setTimeout(flow.add(), 2000);\n    yield flow.wait(); //Wait for the second setTimeout to finish\n\n    console.timeEnd('time'); //3 seconds\n});\n```\n\n### Sleeping in parallel\n\n```javascript\nvar ab = require('asyncblock-generators');\n\nab(function*(flow){\n    console.time('time');\n\n    setTimeout(flow.add(), 1000);\n    setTimeout(flow.add(), 2000);\n    yield flow.wait(); //Wait for both setTimeouts to finish\n\n    console.timeEnd('time'); //2 seconds\n});\n```\n\n### Trapping results\n\n```javascript\nvar ab = require('asyncblock-generators');\n\nab(function*(flow) {\n    //Start two parallel file reads\n    fs.readFile(path1, 'utf8', flow.set('contents1'));\n    fs.readFile(path2, 'utf8', flow.set('contents2'));\n    \n    //Print the concatenation of the results when both reads are finished\n    console.log(yield flow.get('contents1') + yield flow.get('contents2'));\n    \n    //Wait for a large number of tasks\n    for(var i = 0; i < 100; i++){\n        //Add each task in parallel with i as the key\n        fs.readFile(paths[i], 'utf8', flow.add(i));                                    \n    }\n    \n    //Wait for all the tasks to finish. Results is an object of the form {key1: value1, key2: value2, ...}\n    var results = yield flow.wait();\n    \n    //One-liner syntax for waiting on a single task\n    var contents = yield fs.readFile(path, 'utf8', flow.callback());\n\n\n    //See overview & API docs for more extensive description of techniques\n});\n```\n\n### With source transformation\n\n```javascript\n//asyncblock.enableTransform() must be called before requiring modules using this syntax.\n//See overview / API for more details\n\nvar ab = require('asyncblock-generators');\n\nif (ab.enableTransform(module)) { return; }\n\nab(function*(flow) {\n    //Start two parallel file reads\n    var contents1 = fs.readFile(path1, 'utf8').defer();\n    var contents2 = fs.readFile(path2, 'utf8').defer();\n    \n    //Print the concatenation of the results when both reads are finished\n    console.log(yield contents1 + yield contents2);\n    \n    var files = [];\n    //Wait for a large number of tasks\n    for(var i = 0; i < 100; i++){\n        //Add each task in parallel with i as the key\n        files.push( fs.readFile(paths[i], 'utf8').future() );\n    }\n    \n    //Get an array containing the file read results\n    var results = files.map(function(future){\n        return yield future.result;\n    });\n    \n    //One-liner syntax for waiting on a single task\n    var contents = yield fs.readFile(path, 'utf8').sync();\n    \n    //See overview & API docs for more extensive description of techniques\n});\n```\n\n### Returning results and Error Handling\n\n```javascript\nvar ab = require('asyncblock-generators');\n\nif (ab.enableTransform(module)) { return; }\n\nvar asyncTask = function(callback) {\n    ab(function*(flow) {\n        var contents = yield fs.readFile(path, 'utf8').sync(); //If readFile encountered an error, it would automatically get passed to the callback\n\n        return contents; //Return the value you want to be passed to the callback\n    }, callback); //The callback can be specified as the 2nd arg to asyncblock. It will be called with the value returned from the asyncblock as the 2nd arg.\n                  //If an error occurs, the callback will be called with the error as the first argument.\n});\n```\n\n## API\n\nSee [API documentation](https://github.com/scriby/asyncblock/blob/master/docs/api.md)\n\n## Stack traces\n\nSee [stack trace documentation](https://github.com/scriby/asyncblock/blob/master/docs/stacktrace.md)\n\n## Error handling\n\nSee [error handling documentation](https://github.com/scriby/asyncblock/blob/master/docs/errors.md)\n\n## Formatting results\n\nSee [formatting results documentation](https://github.com/scriby/asyncblock/blob/master/docs/results.md)\n\n## Parallel task rate limiting\n\nSee [maxParallel documentation](https://github.com/scriby/asyncblock/blob/master/docs/maxparallel.md)\n\n## Task timeouts\n\nSee [timeout documentation](https://github.com/scriby/asyncblock/blob/master/docs/timeout.md)\n\n## Concurrency\n\nBoth generators, and this module, do not increase concurrency in nodejs. There is still only one thread executing at a time.\nGenerators are like threads which are allowed to pause and resume where they left off without blocking the event loop.\n\n## Risks\n\n* Generators are fast, but they're not the fastest. CPU intensive tasks may prefer other solutions (you probably don't want to do CPU intensive work in node anyway...)\n\n## Compared to other solutions...\n\nA sample program in pure node, using the async library, and using asyncblock-generators.\n\n### Pure node\n\n```javascript\n\nfunction example(callback){\n    var finishedCount = 0;\n    var fileContents = [];\n\n    var continuation = function(){\n        if(finishedCount < 2){\n            return;\n        }\n\n        fs.writeFile('path3', fileContents[0] + fileContents[1], function(err) {\n            if(err) {\n                throw new Error(err);\n            }\n\n            fs.readFile('path3', 'utf8', function(err, data){ \n                console.log(data);\n                console.log('all done');\n            });\n        });\n    };\n\n    fs.readFile('path1', 'utf8', function(err, data) {\n        if(err) {\n            throw new Error(err);\n        }\n\n        fnishedCount++;\n        fileContents[0] = data;\n\n        continuation();\n    });\n\n    fs.readFile('path2', 'utf8', function(err, data) {\n        if(err) {\n            throw new Error(err);\n        }\n\n        fnishedCount++;\n        fileContents[1] = data;\n\n        continuation();\n    });\n}\n```\n\n### Using async\n\n```javascript\n\nvar async = require('async');\n\nvar fileContents = [];\n\nasync.series([\n    function(callback){\n        async.parallel([\n            function(callback) {\n                fs.readFile('path1', 'utf8', callback);\n            },\n\n            function(callback) {\n                fs.readFile('path2', 'utf8', callback);\n            }\n        ],\n            function(err, results){\n                fileContents = results;                                    \n                callback(err);\n            }\n        );\n    },\n\n    function(callback) {\n        fs.writeFile('path3', fileContents[0] + fileContents[1], callback);\n    },\n\n    function(callback) {\n        fs.readFile('path3', 'utf8', function(err, data){\n            console.log(data);\n            callback(err);\n        });\n    }\n],\n    function(err) {\n        if(err) {\n            throw new Error(err);\n        }\n        \n        console.log('all done');\n    }\n);\n```\n\n### Using asyncblock-generators\n\n```javascript\nvar ab = require('asyncblock-generators');\n\nab(function*(flow){\n    fs.readFile('path1', 'utf8', flow.add('first'));\n    fs.readFile('path2', 'utf8', flow.add('second'));\n    \n    //Wait until done reading the first and second files, then write them to another file\n    fs.writeFile('path3', yield flow.wait('first') + yield flow.wait('second'), flow.add());\n    yield flow.wait(); //Wait on all outstanding tasks\n\n    fs.readFile('path3', 'utf8', flow.add('data'));\n\n    console.log(yield flow.wait('data')); //Print the 3rd file's data\n    console.log('all done');\n});\n```\n\n### Using asyncblock + source transformation\n\n```javascript\n//Requires asyncblock.enableTransform to be called before requiring this module\nvar ab = require('asyncblock-generators');\n\nif (ab.enableTransform(module)) { return; }\n\nab(function*(flow){\n    var first = fs.readFile('path1', 'utf8').defer();\n    var second = fs.readFile('path2', 'utf8').defer();\n    \n    fs.writeFile('path3', yield first + yield second).sync();\n\n    var third = fs.readFile('path3', 'utf8').defer();\n\n    console.log(yield third);\n    console.log('all done');\n});\n```\n\n### No prototypes were harmed in the making of this module","publish_time":1451797437302,"_cnpm_publish_time":1451797437302,"dist-tags":{"latest":"2.2.12"}}