带节点的 Phantomjs 给出 "Promise pending"
Phantomjs with node gives "Promise pending"
当我从命令行运行下面的脚本node script.js
时,结果是:
success
Promise { <pending> }
该页面在 console.log
中从未打开过,谁能解释为什么?
var phantom = require('phantom');
phantom.create().then(function (ph) {
ph.createPage().then(function (page) {
page.open('https://whosebug.com/').then(function (status) {
console.log(status);
var p = page.evaluate(function () {
return document.getElementsByTagName('html')[0].innerHTML
});
console.log(p);
});
});
});
那是因为您将 Promise 赋给了一个变量,而它的结果并没有立即返回。你应该:
page.evaluate(function () {
return document.getElementsByTagName('html')[0].innerHTML;
}).then(function (html) {
console.log(html);
});
此外,为了不迷失在回调地狱中,您可以尝试使用 async/await
方法:
(async () => {
const instance = await phantom.create();
const page = await instance.createPage();
const status = await page.open('https://whosebug.com/');
const html = await page.evaluate(function () {
return document.getElementsByTagName('html')[0].innerHTML;
});
console.log(html);
})();
根据 phantom 维护者指南,这是一种首选方式。
如图所示,page.evaluate returns 一个承诺。
试试下面的代码:
var phantom = require('phantom');
phantom.create().then(function(ph) {
ph.createPage().then(function(page) {
page.open('https://whosebug.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()
});
});
});
});
当我从命令行运行下面的脚本node script.js
时,结果是:
success
Promise { <pending> }
该页面在 console.log
中从未打开过,谁能解释为什么?
var phantom = require('phantom');
phantom.create().then(function (ph) {
ph.createPage().then(function (page) {
page.open('https://whosebug.com/').then(function (status) {
console.log(status);
var p = page.evaluate(function () {
return document.getElementsByTagName('html')[0].innerHTML
});
console.log(p);
});
});
});
那是因为您将 Promise 赋给了一个变量,而它的结果并没有立即返回。你应该:
page.evaluate(function () {
return document.getElementsByTagName('html')[0].innerHTML;
}).then(function (html) {
console.log(html);
});
此外,为了不迷失在回调地狱中,您可以尝试使用 async/await
方法:
(async () => {
const instance = await phantom.create();
const page = await instance.createPage();
const status = await page.open('https://whosebug.com/');
const html = await page.evaluate(function () {
return document.getElementsByTagName('html')[0].innerHTML;
});
console.log(html);
})();
根据 phantom 维护者指南,这是一种首选方式。
如图所示,page.evaluate returns 一个承诺。
试试下面的代码:
var phantom = require('phantom');
phantom.create().then(function(ph) {
ph.createPage().then(function(page) {
page.open('https://whosebug.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()
});
});
});
});