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.

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.