[英]Phantomjs with node gives “Promise pending”
When I run the script below from the command line node script.js
, the result is: 当我从命令行node script.js
运行以下脚本时,结果是:
success
Promise { <pending> }
The page never gets opened in console.log
, can anyone explain why? 该页面永远不会在console.log
打开,任何人都可以解释为什么?
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);
});
});
});
That's because you're assigning Promise to a variable, and it's result is not returned immediately. 这是因为您正在将Promise分配给变量,并且结果不会立即返回。 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/await
方法:
(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. 根据幻像维护者指南,这是一种首选方式。
as displayed, page.evaluate returns a promise. 如图所示,page.evaluate返回一个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()
});
});
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.