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;