Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of dummy and empty jQuery promises

I run multiple animations and perform some action when they're complete, using jQuery promises:

$.when(foo(),  
       bar(),  
       baz())  
 .done(allDone);  

Each function (foo, etc.) returns a jQuery.Promise().

Now say I want to include a function which doesn't animate anything, but its timing is related to the animations - I can't include it in the chain, as it doesn't return a promise.

So I can hack it like so:

function qux() {
  if (something) {
    return $(".whatever")
      .removeClass("bob")
      .addClass("fred")
      .append(/*...do stuff...*/)
      .animate({ left: "+=0" }, 0, callback ) // <-- dummy animation does nothing
      .promise();                             // <-- this is a dummy promise
  }
  else {
    return $().promise();                     // <-- this is an "empty" promise
  }
}

And now I can chain it:

$.when(foo(),  
       bar(),  
       baz(),
       qux())  
 .done(allDone);  

This works. But I'm bending the rules here - are there any gotchas I haven't taken into account, or am I somehow stomping on the fx queue?

UPDATE
As per answers below, the qux() function can be rewritten as:

function qux() {
  if (something) {
    $(".whatever")
      .removeClass("bob")
      .addClass("fred")
      .append(/*...do stuff...*/);
  }
}
like image 631
Bobby B Avatar asked Feb 12 '23 09:02

Bobby B


2 Answers

If you are going to use it with $.when you don't need to return an empty promise. $.when can handle non promises. Demo.

function promise(flag) {
    if(flag) {
        var dfd = $.Deferred();
        setTimeout(function(){
            console.log('promise');
            dfd.resolve();
        }, 1000);
        return dfd.promise();
    }

    console.log('promise');
}

$.when(promise(), promise(true), promise(), 15).done(function(){
    console.log('Done');    
});

And if you want to return an empty promise you can use $.Deferred().resolve().promise()

like image 108
Yury Tarabanko Avatar answered Feb 14 '23 23:02

Yury Tarabanko


If your function is always synchronous - simply do not return a promise:

function qux() {
  if (something) {
    return $(".whatever")
      .removeClass("bob")
      .addClass("fred")
      .append(/*...do stuff...*/);
  }
}

You can still use it in $.when but there is little point since it executes synchronously. You should not return promises from synchronous functions.

However, if your function is sometimes synchronous - it should always return a promise for consistency.

As I said in earlier comments - $.when is perfectly fine with non-promises (it will treat them as promises). So functions that might return promises can be used with $.when however if it is always synchronous it is redundant to do so.

like image 21
Benjamin Gruenbaum Avatar answered Feb 14 '23 23:02

Benjamin Gruenbaum