Use Nightmare.js without ES6 syntax and yield

前端 未结 1 1644
孤城傲影
孤城傲影 2021-02-09 04:39

I built a simple node script using nightmare.js to scrape websites

var Nightmare = require(\'nightmare\');
var vo = require(\'vo\');

vo(run)(function(err, resul         


        
相关标签:
1条回答
  • 2021-02-09 04:54

    The docs are horrible, but it seems that Nightmare is based on thenables. I didn't find much information on the callback interface either, but that would lead to an indentation pyramid anyway.

    So your best bet is to use promises, just choose any library that roughly follows the ES6 standard (they all are usable in non-ES6 environments as well).

    You can easily transform your linear generator code into a promise chain, just replace every yield by a then call:

    var Nightmare = require('nightmare');
    var Promise = require('…');
    
    var x = Date.now();
    var nightmare = Nightmare();
    Promise.resolve(nightmare
      .goto('http://google.com')
      .evaluate(function() {
          return document.getElementsByTagName('html')[0].innerHTML;
    })).then(function(html) {
        console.log("done in " + (Date.now()-x) + "ms");
        console.log("result", html);
        return nightmare.end();
    }).then(function(result) {
        …
    }, function(err) {
       console.error(err); // notice that `throw`ing in here doesn't work
    });
    
    0 讨论(0)
提交回复
热议问题