AlertifyJS icon indicating copy to clipboard operation
AlertifyJS copied to clipboard

Support for promises

Open markwoon opened this issue 9 years ago • 4 comments

It would be nice if .confirm() and .prompt() could return a promise instead of having to provide callbacks.

markwoon avatar Nov 11 '16 21:11 markwoon

Yes! Promises highly needed!

ghost avatar Feb 21 '17 06:02 ghost

I made a quick and dirty wrapper to make .prompt thenable. You can adapt this to confirm or any of the other alertify methods as well. The only problem would be that you'd lose the DOM node that get passed through e because Promise doesn't allow passing multiple values through resolve.

const promisifyPrompt = (title, description, defaultValue) => new Promise((resolve, reject) => {
    alertify.prompt(
      title,
      description,
      defaultValue,
      (e, value) => resolve(value),
      reject
      );
  });

You can use it like:

promisifyPrompt(title, description, defaultValue)
.then(
  value => {/* success handler */},
  err => {/* error handler */}
);

or

promisifyPrompt(title, description, defaultValue)
.then(value => {/* success handler */})
.catch(err => {/* error handler */})

juliepanda avatar Mar 30 '17 19:03 juliepanda

Thanks @juliepanda

If you need the event, simply resolve a result (e, value) => resolve({e,value}), then:

promisifyPrompt('title', 'description', 'defaultValue')
.then(({e, value}) => {/* success handler */})
.catch(err => {/* error handler */})

MohammadYounes avatar Mar 30 '17 19:03 MohammadYounes

Just thought this would help someone. I took a little different approach.

Now the below is using a confirm dialog box. It is also using typescript which can be converted to javascript faily easy:

import * as alertify from 'alertifyjs';

export enum ConfirmResult {
  Ok = 1,
  Cancel
}

export function promisifyConfirm(title: string, message: string, options = {}): Promise<ConfirmResult> {

  return new Promise<ConfirmResult>((resolve) => {
    alertify.confirm(
      title,
      message,
      () => resolve(ConfirmResult.Ok),
      () => resolve(ConfirmResult.Cancel)).set(Object.assign({}, {
        closableByDimmer: false,
        defaultFocus: 'cancel',
        frameless: false,
        closable: false
      }, options));
  });
}

Now using promisifyConfirm:

  async myFunction() {
    const confirmResult = await promisifyConfirm('My title', 'My message');
    // confirmResult wil be ConfirmResult.Ok for Ok and ConfirmResult.Cancel for Cancel
  }

mastrauckas avatar Nov 20 '17 16:11 mastrauckas