Node.js flow control

  • View
    1.365

  • Download
    0

Embed Size (px)

DESCRIPTION

淺談Node.js中流程控制的概念與相關套件

Text of Node.js flow control

  • 1. Node.js Flow Control MiCloud - Simon

2. .... 3. node.js text editor command line tool coffee (>. 0) { main(); } }); } main(); (1)CallLoop queue callrequest... 15. callee/caller 16. (2)process.nextTick + callee var request = require('request'); var queue = ['http://www.google.com','http://micloud.tw','http://tw.yahoo.com']; process.nextTick(function fn1(){ var url = queue.pop(); console.log('Processing %s...', url); var _callee = arguments.callee; request.get(url, function(e,r,d){ if(e) console.log(e); console.log('[%s] word count: %s', url, d.length); if(queue.length > 0) process.nextTick(_callee); }); }); queue callrequest... Scopecallee ... 17. 3rd party modules Step, q, node-promise 18. Github: http://github.com/creationix/step.git Step 19. Step var Step = require('step'); Step( function step1() { console.log('Step1...'); throw 'error..'; //step2arguments[0] return 123; //return }, function step2() { console.log('Step2...'); console.log(arguments); // return 223; }, function step3() { console.log('Step3...'); console.log(arguments); } ); 20. var request = require('request'); var queue = ['http://www.google.com', 'http://micloud.tw','http://tw.yahoo.com']; var Step = require('step'); Step( function step1() { console.log('Step1...'); getUrl(queue[0], this); }, function step2() { console.log('Step2...'); getUrl(queue[1], this); }, function step3() { console.log('Step3...'); getUrl(queue[2], this); } ); Step function getUrl(url, callback) { //console.log('Processing url:%s...', url); request.get(url, function(e,r,d){ if(e) console.log(e); console.log('[%s] word count:%s', url, d.length); callback(e,d.length); }) } 21. - parallel() Step( // Loads two files in parallel function loadStuff() { fs.readFile(__filename, this.parallel()); fs.readFile("/etc/passwd", this.parallel()); }, // Show the result when done function showStuff(err, code, users) { if (err) throw err; console.log(code); console.log(users); } ) 22. - group() Step( function readDir() { fs.readdir(__dirname, this); }, function readFiles(err, results) { if (err) throw err; var group = this.group(); // Create a new group results.forEach(function (filename) { fs.readFile(__dirname + "/" + filename, 'utf8', group()); }); }, function showAll(err , files) { if (err) throw err; console.dir(files); } ); 23. Step Stepcallback functioninput callbackstepreturn step(ex: step2)return (ex: web app) step functionreturn 24. CommonJS - Promises/A Q Works in both NodeJS and browsers, compatible with jQuery, thenable, and usable as remote objects via message passing RSVP.js A lightweight library that provides tools for organizing asynchronous code when.js Compact promises with joining and chaining node-promise Promises for NodeJS jQuery 1.5 is said to be 'based on the CommonJS Promises/A design'. ForbesLindesay/promises-a A bare bones implementation of Promises/A intended to pass https://github.com/domenic/promise- tests while being as small as possible WinJS / Windows 8 / Metro 25. q Github: https://github.com/kriskowal/q : https://github.com/kriskowal/q/wiki/Examples-Gallery 26. q npm install q --save 27. q Q.delay Q.defer Q.nfcall Q.nfapply Q.ninvoke Q.npost ... 28. var Q = require('q') , request = require('request') , queue = ['http://www.google.com','http://micloud.tw','http://tw.yahoo.com']; var fn = function(url) { var deferred = Q.defer(); request.get(url, function(e,r,d){ console.log('[%s] word count:%s', url, d.length); deferred.resolve(); }); return deferred.promise; }; Q.allResolved( [ fn(queue[0]), fn(queue[1]), fn(queue[2]) ] ) .then(function(){ console.log(end...) }).done(); q q 29. (skip) var out = function (x, y, z) { var d = Q.defer(); console.log('x:%s, y:%s, z:%s', x, y, z); d.resolve(); return d.promise; }; Q.allResolved([fn(queue[0]), fn(queue[1]), fn(queue[2])]) .spread(out) .then(function(){ console.log('end...'); }) .done(); spread 30. node-promise Github: https://github.com/kriszyp/node-promise 31. node-promise npm install node-promise --save 32. var Promise = require("node-promise").Promise , request = require('request'); var p = new Promise(); function step1(){ request.get("http://www.google.com", function(e,r,d){ console.log('>>1'); p.resolve(d); }); } step1(); p.then(function(d){ console.log('>>2'); console.log('word count:%s', d.length); }, function(err){ console.log(err); } ) node-promise then resolve 33. var Promise = require("node-promise").Promise , request = require('request') var queue = ["http://www.google.com", "http://micloud.tw", "http://tw.yahoo.com"]; var p; function step1(url){ p = new Promise(); request({ url : url, method : "GET" }, function(e,r,d){ console.log('>>url:%s', url); p.resolve(d); }); } step1(queue[0]); step1(queue[1]); promise(p)scope runtime exception 34. var Promise = require("node-promise").Promise , request = require('request') , util = require('util') var site = http://odf.micloud.tw var url = site + '/odf/datasets' var url_detail = site + '/odf/%s/field'; function step1(url){ var p = new Promise(); request({ url : url, method : "GET" }, function(e,r,d){ p.resolve(JSON.parse(d)); }); return p; } step1(url) .then(function(d){ for(var i = 0 ; i< d.length ; i++){ step1(util.format(url_detail, d[i])) .then(function(d){ console.log(d); }); } }) return promisethen function scopepromise 35. Web Flow Control expressjs 36. ExpressJS next() 37. authfilter //req.headers.auth function authfilter(req, res, next){ if(req.headers.auth == 'demo') next(); //nextfilter else //statusCode res.send(401, 'Auth Error!'); } //routingroute app.get('/users', authfilter, user.list); 38. Reference http://opennodes.arecord.us http://calculist.org/blog/2011/12/14/why- coroutines-wont-work-on-the-web/ http://wiki.commonjs.org/wiki/Promises/A https://github.com/basicallydan/q- examples/blob/master/wait-for-multiple- promises.js https://github.com/kriskowal/q/wiki/API- Reference 39. End...