19. Step的用法
var Step = require('step');
Step(
function step1() {
console.log('Step1...');
throw 'error..'; //這個會掉到step2的arguments[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);
}
);
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
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來接收執
行結果值