1

I saw this code in Angular Material web site :

function querySearch (query) {
      var results = query ? self.states.filter( createFilterFor(query) ) : self.states,
          deferred;
      if (self.simulateQuery) {
        deferred = $q.defer();
        $timeout(function () { deferred.resolve( results ); }, Math.random() * 1000, false);
        return deferred.promise;
      } else {
        return results;
      }
    }

Can anyone explain whats happening here ?

if query is not null we call the filter otherwise we return the states and what is that ",deffered" part ?

defered has not created yet and we can't return multiple values either!

So what is the explanation for this code ?

The code is here: https://material.angularjs.org/latest/demo/autocomplete The first one (Basic Usage)

1 Answer 1

3

This is why ternaries are bad for readability. That comma has nothing to do with the ternary, since it's attached to a variable declaration.

All this is doing is declaring the (undefined) variable deferred.

You can declare variables multiple at a time with the comma syntax like so:

var x = 4,
    y = 7,
    z = Math.random();
Sign up to request clarification or add additional context in comments.

4 Comments

Welcome to the world of job security, write code so bad and so complex they have no choice but keep you!
How can we sometimes return actual result and sometimes a promise ? How can we distinguish the result at the caller side?
You shouldn't force yourself into that situation. Since a good result is a promise, you should have your else return a rejected Promise value, so that no matter what, the result can be then'd and it doesn't create a weird scope on your return value
Thanks for the clarifications.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.