用PhantomJS桥接序列化function
我有一个链接数组使用链接参数的function,由PhantomJS刮取数据。 如何实现这个function? 这对于 statemant一次运行paralely 3函数,我recive 事件错误 。
在这种情况下,它适合使用asynchronous ,但它如何使用系列? 运行函数的时间总是不一样,但是asynchronous应该如何理解,完成并从新的URL开始?
var phantom = require('phantom') , async = require('async'); var urls = [ 'http://en.wikipedia.org/wiki/Main_Page', 'http://es.wikipedia.org/wiki/Wikipedia:Portada', 'http://de.wikipedia.org/wiki/Wikipedia:Hauptseite' ]; async.mapSeries(urls, getTitle, function(err, result){ console.log(result); }) function getTitle (link, callback) { phantom.create(function(ph) { return ph.createPage(function(page) { return page.open(link, function(status) { return page.evaluate((function() { return document.title; }), function(result) { callback(null, result); return ph.exit(); }); }); }); }); };
我会尝试像这样的:
var links = [] var _ph function init(cb) { phantom.create(function(ph) { //for each link in links call doStuff() _ph = ph doStuff(ph, link, cb) }) } function doStuff(ph, link, cb) { ph.createPage(function(page) { //does things in parallel? page.open(link, function(status) { page.evaluate((function() { document.title; }), function(result) { cb(null, result); page.close(); }); }); } var counter = links.length var titles; function results(err, res) { titles.push(res) if(--counter == 0) { //done _ph.exit() } } init(results)
可能不工作的代码(我在这里写的),但我希望你明白了。 如果您只想使用1页,如:
var links = [] var _ph var _page function init(cb) { phantom.create(function(ph) { _ph = ph ph.createPage(function(page) { _page = page doStuff(link, cb) } }) } function doStuff(page, link, cb) { page.open(link, function(status) { page.evaluate((function() { document.title; }), function(result) { cb(null, result); page.close(); }); }); } var counter = links.length var titles; function results(err, res) { titles.push(res) if(--counter == 0) { //done _ph.exit() return } doStuff(links[counter], results) } init(results)
- 使用node.js +asynchronous模块从同步callback创build同步循环
- NodeJs:使用请求url的asynchronous – Post方法发送响应之前执行的所有url
- 将parameter passing给async.js任务
- 使用Node.js,Async和Formidable进行error handling
- Async.js – 并行真的平行吗?
- async.each嵌套在async.waterfall中
- asynchronous瀑布不正确保存与mongoose
- 有关node.js中的async.waterfall的问题
- 在NodeJS中插入一个大型的csv文件,200,000行+到MongoDB中