1

How could I simplify the following code? I suspect that it can be simplified by using the $.Deferred class, but I don't know how.

if (condition) { $.get('url').done(function () { done(); }); } else { done(); } 

I don't want to repeat the done() function twice.

0

1 Answer 1

1

The typical way to simplify this sort of code is to create an "empty" resolved promise that you can use in place of the "real" promise if you don't need to get() the url.

I don't use jQuery much, but I believe that would look like this:

var promise = condition ? $.get('url') : $.Deferred().resolve().promise(); promise.done(function () { done(); }); 

In addition to not repeating the done() call, this also has the advantage of being always asynchronous. Your current code appears to be sometimes synchronous and sometimes asynchronous, which is not a good thing.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.