javascriptnightmare

Nightmare JS not ending with reduce function


How can I end the nightmare instance with the following code.

*I guess it has some time conflict with reduce function?

Reference - I used the logic from "Vanilla JS" section - https://github.com/rosshinkley/nightmare-examples/blob/master/docs/common-pitfalls/async-operations-loops.md - I tried this solution, but wasn't able to be successful - https://github.com/segmentio/nightmare/issues/546

const Nightmare = require('nightmare')
const nightmare = Nightmare({
  show: true
})

nightmare
  .goto('https://www.cnn.com/')
  .title()
  .then((x) => {

    console.dir(x);

    var urls = ['http://google.com', 'http://yahoo.com'];
    urls.reduce(function(accumulator, url) {
      return accumulator.then(function(results) {
        return nightmare.goto(url)
          .wait('body')
          .title()
          .then(function(result){
            results.push(result);
            return results;
          });
      });
    }, Promise.resolve([])).then(function(results){
        console.dir(results);
        nightmare.end(); //not ending
    })
  })

Solution

  • reduce returns Promise and you should end all after resolving it, not in initial.

    const Nightmare = require('nightmare')
    const nightmare = Nightmare({
      show: true
    })
    
    nightmare
      .goto('https://www.cnn.com/')
      .title()
      .then((x) => {
    
        console.dir(x);
        var results = [];
    
        var urls = ['http://google.com', 'http://yahoo.com'];
        var promise = urls.reduce((accumulator, url) => {
          return accumulator.then(() => {
            return nightmare.goto(url)
              .wait('body')
              .title()
              .then((result) => {
                results.push(result);
                console.log(results);
              });
          });
        }, Promise.resolve());
    
        promise.then(() => {
          console.dir(results);
          return nightmare.end(); //not ending
        })
      })