segment-boneyard/nightmare

refactor: Simplify and improve the queue

Open

#1.393 geöffnet am 28. Feb. 2018

Auf GitHub ansehen
 (0 Kommentare) (0 Reaktionen) (0 zugewiesene Personen)JavaScript (1.076 Forks)batch import
3.xHelp Wantedenhancement

Repository-Metriken

Stars
 (19.507 Stars)
PR-Merge-Metriken
 (Keine gemergten PRs in 30 T)

Beschreibung

Now that promises are widespread, we can revisit the queueing logic and simplify it a lot. I think this can be done in a non-breaking way. It's basically just one long promise chain, with a little "thenable" magic to support chaining. Here's an example implementation:

function Nightmare(options) {
  if (!(this instanceof Nightmare)) return new Nightmare(options)
  this._options = options || {}
  this._queue = Promise.resolve()
}

/**
 * enqueues the actions
 *
 * @api private
 */

Nightmare.prototype._enqueue = function(fn) {
  this._queue = this._queue.then(() => new Promise(fn))
  return this
}

/**
 * Nightmare implements .then() to create a "thenable"
 */

Nightmare.prototype.then = function(success, failure) {
  return this._queue.then(success).catch(failure)
}

/**
 * Nightmare implements .catch() to create a "thenable"
 */

Nightmare.prototype.catch = function(failure) {
  return this._queue.catch(failure)
}

/**
 * Goto action
 */

Nightmare.prototype.goto = function(url) {
  return this._enqueue((resolve, reject) => {
    // goto implementation
  })
}

Contributor Guide