Nightmare JS 没有以 reduce 函数结束

Nightmare JS not ending with reduce function

如何使用以下代码结束噩梦实例。

*我猜它与 reduce 功能有一些时间冲突?

参考 - 我使用了 "Vanilla JS" 部分的逻辑 - https://github.com/rosshinkley/nightmare-examples/blob/master/docs/common-pitfalls/async-operations-loops.md - 我试过这个解决方案,但未能成功 - 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
    })
  })

reduce returns Promise 并且你应该在解决它之后全部结束,而不是在最初。

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