[英]Best way to pass down data in a series of functions?
我正在使用下面的代码在Node.js Web爬虫应用程序上工作,并尝试按功能定向我的代码。 见下文:
const Promise = require('bluebird');
const fetch = require('node-fetch');
const cheerio = require('cheerio');
const scrapeUri = uri => fetch(uri); // how should i pass the uri from here
const fetchURIs = URIs => Promise.all(URIs.map(scrapeUri));
const getBodies = pages => Promise.all(pages.map(page => page.text()));
const toSource = source => cheerio.load(source);
const shouldScrape = ($) => {
const shouldIndex = $('meta[name="robots"]').attr('content');
if (['noindex', 'nofollow'].indexOf(shouldIndex) !== -1) {
return false;
}
return true;
};
const objectifyContent = ($) => { // to be accessed here
return {
meta: {
index_timestamp: new Date(),
title: $('title').html(),
// TODO: this will totally fail in some instances, need to pass uri from initial instance
uri: $('link[rel="canonical"]').attr('href'),
description: $('meta[name="description"]').attr('content'),
},
};
};
在objectifyContent
,从初始scrapeUri
访问uri而不是尝试通过访问规范来获取页面url的纯方法是什么? 我知道可以设置变量并使其在范围内继承的某些方式,但是我想知道在Node.js上下文中是否存在更干净,更实用的执行方式。
调用者将类似于: fetchUris(myUris).then(values => getBodies(values).then(sources => res.send(sources.map(toSource).filter(shouldScrape).map(objectifyContent));)
修改此scrapeUri
以将URL传递给promise,并相应地修改您的处理程序
const scrapeUri = uri => fetch(uri).then(
webpage => [uri, webpage]
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.