0

I'm trying to get a better grasp on jQuery promises. I've created a toy problem / repro (which reinvents the validation-wheel, for learning purposes) that looks like this:

$(function() {
  "use strict";

  function isStep1Valid() { 
    return !!$("input").val();
  }
  
  function leaveStep1() {
    if (!isStep1Valid()) {
      return $.when(null).fail();            // <-- A. this seems off
    }  
    return $(".step1").slideUp().promise();
  }
  
  function enterStep2() {
    return $(".step2").slideDown().promise();
  }
  
  function handleFail() {
    return $(".step1 .error").slideDown().promise();
  }
  
  function handleClick() {
    leaveStep1()
      .fail(handleFail)                      // <-- B. this seems off
      .done(enterStep2);
  }

  $("button").on("click", handleClick);
});
.step { background-color: #ddd; padding: 10px; }
.hidden { display: none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="step step1">
  Step 1
  <input placeholder="enter anything">
  <button>next</button>
  <div class="error hidden">ERROR!</div>
</div>
<div class="step step2 hidden">
  Step 2...
</div>

Currently, in the above:

  • Entering input text and then clicking "next" works as expected;
  • Entering no input and clicking "next" incorrectly shows step2 instead of the "error".

I'm not doing the correct thing at A and B I think, but I'm not sure how to fix this. Heck, I'm not even sure what the correct search terms or question title for my problem are.

Heck, I might even have an XY-problem, but then I just don't see what "X" is. Something close to "X" / the origingal thing I'm trying to get working:

  • On button click I want to try and leave step 1...
    • ...if leaving step 1 fails: show an error;
    • ...if it is successful: show step 2;
Jeroen
  • 60,696
  • 40
  • 206
  • 339
  • @Bergi Thanks for linking to the [other question](http://stackoverflow.com/q/10843297/419956). I can see how it could be considered a dupe, but I'm having a *very* hard time translating the answer there to an answer for my scenario, because the other question's context is entirely about `$.ajax` and my context seems quite different. Do you have any suggestions how we could resolve this? Would you consider un-mjollniring this question if I explain how I failed to apply the answer from linked question? (asking *before* I go and do all the work for that...). Or do you have another suggestion? – Jeroen Apr 13 '16 at 12:50
  • I think the `$ajax(…).then` callback is exactly the same as your `leaveStep1`. But sure, go for an edit, either we can resolve it in the comments or I'll reopen and answer – Bergi Apr 13 '16 at 12:52
  • I'll ponder your comment for a bit and will try once more to map that answer to my context. If I fail I'll edit and ping you. Thanks for being helpful! – Jeroen Apr 13 '16 at 12:58

0 Answers0