javascript - 图像抓取器 nodeJS。如何将回调函数发送到结果数组

标签 javascript node.js web-scraping promise

我尝试构建简单的应用程序来构建 img-parser 并开始使用库图像抓取器(node-image-scraper)。并面临一个问题。问题是:我怎样才能得到最终的对象数组

scraper.scrape(function(image) {
        images_list.push(image);
})

promises - 不起作用,我试图在函数的参数内部发送回调,它也没有给我结果。

最佳答案

如果你想要一个 promise ,那么 scraper#scrape() 可以被 promise 。

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();
    });
}

未经测试

调用,例如:

const scraper = new Scraper('whatever');

scraper.scrapeAsync(30000).then((images) => {
    // process the `images` array here.
});

修改图像抓取器源以发出“错误”事件而不是记录错误应该相当简单。您可能需要针对 page_error(致命)和 image-error(非致命)的单独事件。

提交拉取请求似乎没有什么意义 - 最后一次更新是 2 年前。

关于javascript - 图像抓取器 nodeJS。如何将回调函数发送到结果数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42475006/

相关文章:

mysql - 与 MySQL 相比,MongoDB 慢得多——基本的 find() 方法

node.js - 错误: Cannot find module 'gulp-serve'

javascript - typescript:读取 Node js 中的类装饰器文件

javascript - ExpressJS - 使路由只能从内部重定向访问

javascript - Angular 2 : Contenteditable div doesn't work as expected

css - 如何使用 Stylus 创建多个 CSS 文件?

python - 从多个链接中获取数据,同时存储在 Scrapy 中的一个项目中

html - 在嵌套表上使用 rvest 时出现问题

python - 无法使用 scrapy 抓取结果列表上的数据

javascript - 无法将未定义或 null 转换为 react 中的对象