16.07.2017 Views

AngularJS Essentials

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 4<br />

if (result.length > 0) {<br />

successCallback(result);<br />

} else {<br />

errorCallback("No results were found!");<br />

}<br />

}, 1000);<br />

};<br />

var _matches = function (car, criteria) {<br />

return angular.toJson(car).indexOf(criteria) > 0;<br />

};<br />

return {<br />

filter: _filter<br />

}<br />

});<br />

In order to call the filter function properly, we need to pass both callbacks to<br />

perform the success, as follows:<br />

controllers.js<br />

$scope.searchCarsByCriteria = function (criteria) {<br />

carSearchService.filter($scope.cars, criteria, function (result) {<br />

$scope.searchResult = result;<br />

}, function (message) {<br />

$scope.message = message;<br />

});<br />

};<br />

However, there are situations in which the numerous number of callbacks,<br />

sometimes even dangerously chained, may increase the code complexity and<br />

transform the asynchronous algorithms into a source of headaches.<br />

To figure it out, there is an alternative to the massive use of callbacks—the promise<br />

and the deferred patterns. They were created a long time ago and are intended to<br />

support this kind of situation by returning a promise object, which is unknown while<br />

the asynchronous block is processed. As soon as something happens, the promise is<br />

deferred and notifies its handlers. It is created without any side effects and returns<br />

the promise.<br />

[ 99 ]<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!