无论如何,如果要使用Promise,请使用
request-promise和
fs-promise简化代码,而不要重复使用函数。
var rp = require('request-promise');var fsp = require('fs-promise');var onion_url = "https://www.reddit.com/r/theonion";var not_onion_url = "https://www.reddit.com/r/nottheonion";function parse(html) { var result = ''; var $ = cheerio.load(html); $("div#siteTable > div.link").each(function(idx) { var title = $(this).find('p.title > a.title').text().trim(); console.log(title); result += title + 'n'; }); return result;}var append = file => content => fsp.appendFile(file, content);rp(onion_url) .then(parse) .then(append('onion.txt')) .then(() => console.log('Success')) .catch(err => console.log('Error:', err));rp(not_onion_url) .then(parse) .then(append('not_onion.txt')) .then(() => console.log('Success')) .catch(err => console.log('Error:', err));这未经测试。



