-1

Below jQuery's deferred fail() only executes once, why?

var dfd = $.Deferred();

$('button').on('click', function(){

    if(typeof lorem === 'undefined') {
        return dfd.reject();
    }
});

dfd.fail(function(){
    alert('Variable lorem is not defined');
});

https://codepen.io/bartclaeys/pen/EOooKy

Expected behavior: When you click the button repeatably, the alert should fire repeatedly.

bart
  • 14,958
  • 21
  • 75
  • 105
  • So it does exactly what it's supposed to do? [promises cannot be resolved or rejected more than once.](http://api.jquery.com/jQuery.Deferred/) – Kevin B Nov 20 '18 at 23:50
  • @KevinB I want it to fire multiple times, so I guess I need to reset the promise somehow? – bart Nov 20 '18 at 23:51
  • 1
    You need something other than a promise. Not a promise. such as an event. or simply a function. – Kevin B Nov 20 '18 at 23:52
  • Just define the deferred within the click event and have the fail handler as a global function, or within the click also, that's up to you – David Espino Nov 20 '18 at 23:53
  • @DavidEspino Trying, not working... – bart Nov 20 '18 at 23:56
  • Replace your `return` line with `alert('Variable lorem is not defined');`. Either your example WAY oversimplifies your problem, or you are way over complicating it with your solution to said problem. – Kevin B Nov 21 '18 at 00:00
  • @KevinB Basically not using deferred at all? – bart Nov 21 '18 at 00:01
  • Yes, deferred (aka promises) are the wrong tool for this job. – Kevin B Nov 21 '18 at 00:02
  • @KevinB Care to explain why? My code isn't as simple as above, various vars are being checked whether they are available. – bart Nov 21 '18 at 00:05
  • If you need the reject to happen more than once, it's the wrong tool. plain and simple. You can't reset it. You can replace it with a new promise, but then you've got to rebind all the callbacks too... which is pointless. just use a function. – Kevin B Nov 21 '18 at 00:06
  • @KevinB Bizarre, like a click on a button executing an AJAX call can only be rejected once... – bart Nov 21 '18 at 00:08
  • Well, yes, but each click would be generating a new promise, one per ajax call. That's entirely different from what you showed in your question. – Kevin B Nov 21 '18 at 00:08
  • @KevinB See my answer below. – bart Nov 21 '18 at 00:10

1 Answers1

-1

Answering my own question, below works:

$('button').on('click', function(){

    var dfd = $.Deferred();

    dfd.fail(function(){
        alert('Error');
    });

    if(typeof lorem === 'undefined') {
        return dfd.reject();
    }
});
bart
  • 14,958
  • 21
  • 75
  • 105