13 July, 2014
0 Comments
1 category
Q or $q
If you are using Q or $q you can pas extra data to the then function by using the $q.all function:
function execute() { var firstNames = ['Bo', 'Cris', 'Richard']; $q.all({ firstNames: $q.when(firstNames), lastNames: $http.get('/api/lastNames') }).then(handleGetLastNamesResult) } function handleGetLastNamesResult(data) { var firstNames = data.firstNames; var lastNames = data.lastNames; }
jQuery
In this example I will use jQuery, but the same pattern works for $q and Q.
You can make an Ajax request in jQuery like, so:
var app = (function () { var self = {}; self.handleGetResult = function (data) { // Do something with the result from the server. }; self.start = function () { var promise = $.ajax({ url: 'https://api.github.com/users/roelvanlisdonk/repos', type: 'GET' }); $.when(promise).then(self.handleGetResult); }; self.start(); return self; })();
The function passed to the .then function can only contain one parameter and will contain the data returned form the server. If you want to pass the function called by the “.then” function some additional data. You can use the following pattern:
var app = (function () { var self = {}; self.handleGetResult = function (data) { var resultHandler = this; var additionalData = resultHandler.getAdditionalData(); // Do something with the result from the server and the additional data. }; self.ResultHandler = function (additionalData, handleResultFunc) { var self = this; var _additionalData = additionalData; var _handleResultFunc = handleResultFunc; self.getAdditionalData = function () { return _additionalData; }; self.handleResult = function (data) { _handleResultFunc.call(self, data); }; return self; }; self.start = function () { var promise = $.ajax({ url: 'https://api.github.com/users/roelvanlisdonk/repos', type: 'GET' }); var handler = new self.ResultHandler("Some extra data", self.handleGetResult); $.when(promise).then(handler.handleResult); }; self.start(); return self; })();
Category: Uncategorized
Thanks for this. Do you have to wrap firstNames in $q.when? Can’t you just pass in the array directly and access it inside your callback?