Context:
I'm using node-horseman to web scrape. The situation is that after each action i make the headless browser take, i generally want to see the results.
The results can be seen by running
horseman
.open('http://www.google.com')
.html()
.then((html)=>{
return new Promise((resolve, reject)=>{
console.log(html);
fs.writeFile("result.html", html)
resolve();
})
})
.screenshot("result.png")
.close();
Which creates writes the html to result.html and writes a screenshot of the rendered page to result.png.
Question:
instead of copy pasting that string of 4 promises, is it possible to assign that string of promises to a variable or method and then apply it? E.g.,
horseman
.open('http://www.google.com')
.preview_result()
Where
function preview_result(){
return html()
.then((html)=>{
return new Promise((resolve, reject)=>{
console.log(html);
fs.writeFile("result.html", html)
resolve();
})
})
.screenshot("test.png")
.close();
}
or
var preview_result =
html()
.then((html)=>{
return new Promise((resolve, reject)=>{
console.log(html);
fs.writeFile("result.html", html)
resolve();
})
})
.screenshot("test.png")
.close();
You can define a reusable function in such a way that it takes a Promise as an input:
This function will return something that was returned by
close()function and if it was a Promise, you can simply continue a Promise chain.You can use it this way:
Another approach is to use apply:
But I don't see any significant advantages in it.