简体   繁体   中英

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

I'm creating JSON data and I am having trouble changing the sub property of my data.

For my first promise, I want each object's sub property to contain the value theonion . For the second promise, I want it to be nottheonion . However, both files (onion.json and nottheonion.json) end up being identical, both containing data from r/nottheonion

Here is my code.

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

Try this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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