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

Javascript Nodejs:如何使用不同的参数调用函数两次?,javascript,json,node.js,Javascript,Json,Node.js,我正在创建JSON数据,更改数据的sub属性时遇到问题 对于我的第一个承诺,我希望每个对象的sub属性包含值theonion。对于第二个承诺,我希望它是而不是nion。但是,这两个文件(onion.json和nottheonion.json)最终都是相同的,都包含来自r/nottheonion的数据 这是我的密码 function parse(html, subreddit) { var $ = cheerio.load(html); $("div#siteTable > d

我正在创建JSON数据,更改数据的
sub
属性时遇到问题

对于我的第一个承诺,我希望每个对象的
sub
属性包含值
theonion
。对于第二个承诺,我希望它是
而不是nion
。但是,这两个文件(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;
}
试试这个:

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;
}

它起作用了。这不是我想要的方式,但我意识到我可以只拥有一个包含r/theonion和r/nottheonion的JSON文件,这就是代码所做的。它使用来自两个子项的数据写入两个文件。谢谢。我不确定,但是var append=file=>content=>fsp.appendFile(file,content);在我看来是不对的。。。。。这不应该是var append=(文件,内容)=>fsp.appendFile(文件,内容);将上一次回调的内容传递给它,它就可以工作了。这不是我想要的方式,但我意识到我可以只拥有一个包含r/theonion和r/nottheonion的JSON文件,这就是代码所做的。它使用来自两个子项的数据写入两个文件。谢谢。我不确定,但是var append=file=>content=>fsp.appendFile(file,content);在我看来是不对的。。。。。这不应该是var append=(文件,内容)=>fsp.appendFile(文件,内容);将上一次回调的内容传递给它,
posts
声明在哪里?您知道两个承诺共享相同的
posts
-array吗?在哪里声明
posts
?您知道这两个承诺共享相同的
帖子
-array吗?