Search code examples
javascriptnode.jsweb-scrapingnightmare

How to end NightmareJs instance after chaining promises?


The examples I see in the docs invoke .end() before .then() is used. such as

nightmare
  .goto('http://yahoo.com')
  .type('form[action*="/search"] [name=p]', 'github nightmare')
  .click('form[action*="/search"] [type=submit]')
  .wait('#main')
  .evaluate(function () {
    return document.querySelector('#main .searchCenterMiddle li a').href
  })
  .end()
  .then(function (result) {
    console.log(result)
  })
  .catch(function (error) {
    console.error('Search failed:', error);
  });

However, I'm trying to do it like...

...
.then(function () {...})
.end()

But I get an error stating that .end doesn't exist.

I've also tried the below, which doesn't throw an error but it will cause nightmare to hang.

...
.then(function () {...})
.then(function () {
  nightmare.end()
});

Solution

  • Per the Github issue discussion

    nightmare.end() must be returned from a chained .then(), and not just invoked.

    ...
    .then(function () {...})
    .then(function () {
      return nightmare.end();
    })