DEV Community

loading...

Discussion on: Have a Handy JS Snippet You Want to Share?

Collapse
prodigalknight profile image
RevanProdigalKnight

Quick-and-easy deferred promise (like from q.defer()) - handy for modal dialogs:

class Deferred {
  constructor() {
    this.promise = new Promise((resolve, reject) => {
      this.resolve = resolve;
      this.reject = reject;
    });
  }
}

// example
function dialog() {
  const deferred = new Deferred();

  // create dialog here
  ...

  // Finally, set up the button click handlers
  dialog.okButton.onclick = deferred.resolve;
  dialog.cancelButton.onclick = deferred.reject;

  return deferred.promise;
}

// Alternatively
function dialog() {
  const { promise, resolve, reject } = new Deferred();

  // etc...

  dialog.okButton.onclick = resolve;
  dialog.cancelButton.onclick = reject;

  return promise;
}

dialog().then(/* success! */, /* cancelled */);

Better than wrapping all of that code inside of a Promise constructor every time, in my opinion.