Reputation: 1802
When I run the script below from the command line node script.js
, the result is:
success
Promise { <pending> }
The page never gets opened in console.log
, can anyone explain why?
var phantom = require('phantom');
phantom.create().then(function (ph) {
ph.createPage().then(function (page) {
page.open('https://stackoverflow.com/').then(function (status) {
console.log(status);
var p = page.evaluate(function () {
return document.getElementsByTagName('html')[0].innerHTML
});
console.log(p);
});
});
});
Upvotes: 0
Views: 595
Reputation: 8467
That's because you're assigning Promise to a variable, and it's result is not returned immediately. You should rather:
page.evaluate(function () {
return document.getElementsByTagName('html')[0].innerHTML;
}).then(function (html) {
console.log(html);
});
Also, to not get lost in callback hell you might try to use async/await
approach:
(async () => {
const instance = await phantom.create();
const page = await instance.createPage();
const status = await page.open('https://stackoverflow.com/');
const html = await page.evaluate(function () {
return document.getElementsByTagName('html')[0].innerHTML;
});
console.log(html);
})();
Which is kind of preferred way according to phantom maintainers guide.
Upvotes: 1
Reputation: 139
as displayed, page.evaluate returns a promise.
try the folowing code :
var phantom = require('phantom');
phantom.create().then(function(ph) {
ph.createPage().then(function(page) {
page.open('https://stackoverflow.com/').then(function(status) {
console.log('test'+status);
var p = page.evaluate(function () {
return document.getElementsByTagName('html')[0].innerHTML
});
p.then(function(pagecontent) {
console.log(pagecontent);
process.exit()
});
});
});
});
Upvotes: 2