johntitus / node-horseman

Run PhantomJS from Node
MIT License
1.45k stars 124 forks source link

How to completely stop horseman on alert? #278

Open aleksai opened 7 years ago

aleksai commented 7 years ago

Hi, trying to stop horseman chain if it receives an alert:

horseman.on('alert', function(msg) {
    return horseman.close()
})

But it's still trying to complete chain till the end. How can I solve it?

awlayton commented 7 years ago

As anyone who understands promises knows, the way to stop a chain is to reject rather than resolve. Then nothing later in the chain will run unless the rejection is handled.

However the bigger problem is that the on alert handler is an event handler, not actually part of the chain of Horseman actions (which is a promise chain).

There is no general way to achieve this. Coming up with a solution would require more knowledge of you specific use-case. I imagine there is another way to achieve your objective without doing this, but maybe not.

AaronLlanos commented 7 years ago

Not sure if you have already solved this problem but as stated above the horseman chain is different from the event listeners. However, you could do something like this:

  var horse = new horseman(), errorCaught
  horse
    .on('error', function (err) {
      errorCaught = err
    })
    .open(url)
    .then(function () {
      return new Promise((resolve, reject) => {
        if (errorCaught) {
          reject(errorCaught)
        } else {
          resolve()
        }
      })
    })
    .... do extra stuff .....
    .close()

I know that this does not fit your exact need but I only hope to shed light on how I have solved a similar issue in the past