我尝试构建简单的应用程序来构建 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/