图像刮板节点JS。 如何将callback函数发送到结果数组
我试图构build简单的应用程序来构buildimgparsing器,并开始使用库图像刮板( 节点图像刮板 )。 并面临一个问题。 问题是:我怎样才能得到最终的对象数组
scraper.scrape(function(image) { images_list.push(image); })
诺言 – 不起作用,我试过在函数参数里面调用它也没给我结果。
如果你想要一个承诺,那么scraper#scrape()
可以promisified。
var Scraper = require("image-scraper"); Scraper.prototype.scrapeAsync = function(ms) { var ref = this; // same coding style as in existing methods. var images = []; return new Promise(function(resolve, reject) { ref.on('image', (image) => { images.push(image) }); ref.on('end', () => { resolve(images) }); // ref.on('error', reject); // unfortunately image-scraper doesn't emit an 'error' event. if(ms !== undefined) { // maybe timeout as substitute for error handler? setTimeout(() = { reject(`image-scraper timed out after ${ms} ms`); }, ms); } ref.scrape(); }); }
未经testing
打电话,例如:
const scraper = new Scraper('whatever'); scraper.scrapeAsync(30000).then((images) => { // process the `images` array here. });
修改image-scraper源来发出“错误”事件而不是logging错误应该是相当简单的。 您可能需要单独的事件page_error
(致命)和image-error
(非致命)。
提交拉取请求似乎没有什么意义 – 最近一次更新是在两年前。
使用scraper.on
方法来侦听end
事件。
请注意,您对.scrape(callback)
叫)的呼叫也可以用.on('image', callback)
代替。
var images = [] scraper.on('image', function (image) { images.push(image) }) scraper.on('end', function () { console.log(images) })