繁体   English   中英

Nodejs:如何使用不同的参数调用两次函数?

[英]Nodejs: How to call a function twice with a different parameter?

我正在创建JSON数据,但我无法更改数据的sub属性。

对于我的第一个承诺,我希望每个对象的sub属性包含值theonion 对于第二个承诺,我希望它不是nottheonion 但是,两个文件(onion.json和nottheonion.json)最终都是相同的,都包含来自r / nottheonion的数据

这是我的代码。

function parse(html, subreddit) {
  var $ = cheerio.load(html);

    $("div#siteTable > div.link").each(function(idx) {
      var title = $(this).find('p.title > a.title').text().trim();
      posts.push({ sub: subreddit, content: title });
    });

  var posts_as_json = JSON.stringify(posts);
  return posts_as_json;
}

var append = file => content => fsp.appendFile(file, content);

rp(onion_url)
  .then(html => parse(html, "onion"))
  .then(append('onion.json'))
  .then(() => console.log('Onion Success'))
  .catch(err => console.log('Error: ', err));

rp(not_onion_url)
  .then(html => parse(html, "nottheonion"))
  .then(append('not_onion.json'))
  .then(() => console.log('Not Onion Success'))
  .catch(err => console.log('Error: ', err));

尝试这个:

function parse(html, subreddit) {
  var p = subreddit;
  var $ = cheerio.load(html);

    $("div#siteTable > div.link").each(function(idx) {
      var title = $(this).find('p.title > a.title').text().trim();
      posts.push({ sub: p, content: title });
    });

  var posts_as_json = JSON.stringify(posts);
  return posts_as_json;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM