Skip to content

Instantly share code, notes, and snippets.

@zeke
Created October 8, 2018 21:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zeke/2b06ef06e2ddaa7e2ec5bf1837b203b8 to your computer and use it in GitHub Desktop.
Save zeke/2b06ef06e2ddaa7e2ec5bf1837b203b8 to your computer and use it in GitHub Desktop.
const cheerio = require('cheerio')
const html = `
<ul>
<li>Hello A</li>
<li>Hello B</li>
<li>Hello C</li>
</ul>
`
const $ = cheerio.load(html)
function parse (input) {
return Promise.resolve(input.replace('Hello', 'Goodbye'))
}
console.log($.html())
Promise.all(
$('li')
.map((i, el) => parse($(el).html()))
.get()
).then(intros => {
console.log(intros)
})
@zeke
Copy link
Author

zeke commented Oct 8, 2018

Here's a variant that actually mutates the $(el) HTML on the fly:

const cheerio = require('cheerio')
const html = `
<ul>
  <li>Hello A</li>
  <li>Hello B</li>
  <li>Hello C</li>
</ul>
`
const $ = cheerio.load(html)

function parse (input) {
  return Promise.resolve(input.replace('Hello', 'Goodbye'))
}

console.log('\n\nBefore')
console.log($.html())

Promise.all(
  $('li')
    .map((i, el) => {
      return parse($(el).html()).then(parsed => {
        return $(el).html(parsed)
      })
    })
    .get()
).then(intros => {
  console.log('\n\nAfter')
  console.log($.html())
})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment