Material Design - Confirmation Dialog - How to work with promises in dialog.listen method?

Viewed 502

Before important actions in my application I'm rendering a MD confirmation dialog to the client.
I want to execute a specific action only if the user clicks on the "Confirm" button.
The way to implement this by MD documentation is with the dialog.listen() method.
Right now I'm sending a callback function and executing it only when the action is 'confirm'.
My code:

const showConfirmationDialog = callbackFunc => {
    const dialog = new MDCDialog(document.querySelector('.mdc-dialog'));

    dialog.open();

    dialog.listen('MDCDialog:closed', e => {
        if (e.detail.action === 'confirm') callbackFunc();
      });
};

The showConfirmationDialog() and the callBackFunc() functions are placed in different files.
Working with callback is fine, but is there any way to use promises in that case?
Something like:

import showConfirmationDialog from '...';

const functionToExecute = () => {
   // Something in here
};

showConfirmationDialog()
    .then(() => functionToExecute());

EDIT: I've tried to do something like that, but it didn't work:

        if (e.detail.action === 'confirm') return Promise.resolve();
1 Answers

You need to return a promise in showConfirmationDialog function. You have 2 choices:

  1. Implement a Promise inside the function to resolve or reject according success or failure cases
  2. Transform the function to a promise with promisify() function.

The second option is only possible if your function uses the "Error First Callback Pattern". Like callback(error, obj), then promisify will convert it to a Promise implementation.

Here is a code to implement the Promise directly, just change the callback to promise:

const showConfirmationDialog = () => {
  const dialog = new MDCDialog(document.querySelector('.mdc-dialog'));

  return new Promise((resolve, reject) => {
    dialog.open();
    dialog.listen('MDCDialog:closed', e => {
      if (e.detail.action === 'confirm') {
        resolve();
      } else {
        reject();
      }
    });
  });
};

---- EDIT ----

The promisification of an Error First Callback Pattern could look like this in your case:

const showConfirmationDialog = callbackFunc => {
  const dialog = new MDCDialog(document.querySelector('.mdc-dialog'));

  dialog.open();

  dialog.listen('MDCDialog:closed', e => {
    if (e.detail.action === 'confirm') callbackFunc();
    else callbackFunc();
  });
};

const showConfirmationDialogPromise = Promise.promisify(showConfirmationDialog);

showConfirmationDialogPromise()
  .then(() => console.log('promise work'));
Related