图像抓取 nodeJS.如何将回调函数发送到结果数组 [英] image-scraper nodeJS. How to send callback function to result array

查看:53
本文介绍了图像抓取 nodeJS.如何将回调函数发送到结果数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I tried to build easy app to build img-parser and started to use library image-scraper(node-image-scraper). And faced with a problem. The question is: How could I get final array of objects

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

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

promises - doesn't work, I tried to send call back inside parameter of functions it also not gave me result.

推荐答案

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

If you want a promise, then scraper#scrape() can be 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();
    });
}

未经测试

调用,例如:

const scraper = new Scraper('whatever');

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

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

It should be reasonably simple to modify the image-scraper source to emit "error" events instead of logging errors. You will probably want separate events for page_error (fatal) and image-error (non-fatal).

提交拉取请求似乎没什么意义 - 上次更新是 2 年前.

There seems to be little point submitting a pull-request - last update was 2 years ago.

这篇关于图像抓取 nodeJS.如何将回调函数发送到结果数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆