Last active
August 19, 2016 10:18
-
-
Save limboinf/e0128fb1fcccb4bf69add2e7643ea177 to your computer and use it in GitHub Desktop.
实现串行化流程控制的思路:按 预期执行顺序 将异步 依次 放入数组中(队列),完成一个任务后按顺序从数组中取出下一个。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Task 1. 判断rss文件是否存在 | |
//Task 2. 解析rss文件 | |
//Task 3. 发起网络请求 | |
//Task 4. 解析rss响应 | |
var fs = require('fs'), | |
request = require('request'), | |
htmlparser = require('htmlparser'), | |
rssPath = './rss.txt'; | |
//Task 1. 判断rss文件是否存在 | |
function checkRssPath() { | |
fs.exists(rssPath, function (exists) { | |
if (!exists) { | |
return next(new Error('Missing Rss file: ' + rssPath)); | |
} | |
next(null, rssPath); | |
}) | |
} | |
//Task 2. 解析rss文件 | |
function getRss() { | |
fs.readFile(rssPath, function (err, data) { | |
if (err) return next(err); | |
data = data.toString().replace(/^\s+|\s+$/g, '').split('\n'); | |
var random = Math.floor(Math.random()*data.length); | |
next(null, data[random]); | |
}) | |
} | |
//Task 3. 发起网络请求 | |
function requestRss(feedUrl) { | |
request({uri: feedUrl}, function (err, res, body) { | |
if (err) return next(err); | |
if (res.statusCode != 200) | |
return next(new Error('Abnormal response status code')); | |
next(null, body); | |
}) | |
} | |
//Task 4. 解析rss响应 | |
function parserRssResponse(rss) { | |
var handler = new htmlparser.RssHandler(); | |
var parser = new htmlparser.Parser(handler); | |
parser.parseComplete(rss); | |
if (!handler.dom.items.length) { | |
return next(new Error('No RSS items found.')); | |
} | |
var item = handler.dom.items.shift(); | |
console.log(item.title); | |
console.log(item.link); | |
} | |
// 按预期执行顺序排列好 | |
var tasks = [ | |
checkRssPath, | |
getRss, | |
requestRss, | |
parserRssResponse | |
]; | |
function next(err, result) { | |
if (err) throw err; | |
//主要利用了 shift方法删除数组的第一个元素,并返回该元素 | |
var currentTask = tasks.shift(); | |
if (currentTask) { | |
currentTask(result); | |
} | |
} | |
function start(){ | |
next(); | |
} | |
start(); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
http://www.techug.com/feed | |
http://ifeve.com/feed/ | |
http://beginman.cn/feed.xml |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
虽然串行了但是执行效率没提升,下一步让异步任务并行执行。同样也是放在数组里,但是顺序无关紧要,只需要一个调度器调度即可。