带节点的Phantomjs给出“Promise pending”

时间:2017-10-15 19:39:04

标签: javascript phantomjs

当我从命令行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://stackoverflow.com/').then(function (status) {
      console.log(status);
      var p = page.evaluate(function () {
        return document.getElementsByTagName('html')[0].innerHTML
      });
      console.log(p);
    });
  });
});

2 个答案:

答案 0 :(得分:1)

那是因为您将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://stackoverflow.com/');

  const html = await page.evaluate(function () {
    return document.getElementsByTagName('html')[0].innerHTML;
  });

  console.log(html);
})();

根据phantom维护者指南,这是一种首选方式。

答案 1 :(得分:1)

显示

,page.evaluate返回一个promise。

尝试下面的代码:

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()
      });
    });
  });
});