6

I got a custom confirm dialog which waits for user input. I'm wrapping it in a promise.

When the user is choosing the "yes" alternative I resolve the promise.

However, when the user chooses no it's not really an error but more that the next task should not be executed.

How should I handle that scenario with the promise? simply not invoke resolve/reject or is there a better approach?

jgauffin
  • 99,844
  • 45
  • 235
  • 372
  • 1
    Well, in my opinion `no` means `reject`, and `reject` doesn't necessarily mean an error, it can just mean that the next action should not happen. – XCS Jun 05 '17 at 08:38
  • 1
    `simply not invoke resolve/reject` would mean the chain stalls! you can reject, with smart code you can do what you need – Jaromanda X Jun 05 '17 at 08:39
  • You could also `resolve` and pass a `boolean`, `true` when user choose "yes", and `false` for "no". – Arg0n Jun 05 '17 at 08:40
  • use a guard flag to control the block of code. But remember to either resolve/reject to complete the chain execution. You can also return a promise inside the chain and design that way to control the execution flow – NiRUS Jun 05 '17 at 08:40
  • @JaromandaX: true. @Cristy: Mozilla suggests that one should always pass an Error object to `reject()`, – jgauffin Jun 05 '17 at 10:13

1 Answers1

10

You could resolve a value and check that value afterwards.

new Promise((resolve, reject) => {
    const userInput = confirm('Do you want to continue?');
    resolve(userInput);
}).then(input => {
    if(input) {
        // Do something
    } else {
        // Do something else
    }
});
Frederik Hansen
  • 506
  • 4
  • 21