Sunday 15 July 2012

javascript - Chained promises in Angular. Wrong input parameter -



javascript - Chained promises in Angular. Wrong input parameter -

i have problems chained promises.

i mocked backend simulate ajax requests.

$httpbackend.whenget('/contacts').respond(function(method,url,data) { console.log("getting contacts"); homecoming [200, contacts, {}]; });

in service contactsservice create ajax phone call , chain handler extract info (which array of contacts) contact index.

self.getcontact = function(index) { var handler = new self.resulthandler(index, self.handlecontactsuccess); homecoming $http.get("/contacts").then(handler.handleresult, self.handleerror); } self.handlecontactsuccess = function( response ) { var resulthandler = this; var index = resulthandler.getadditionaldata(); if (index < response.data.length) { return( response.data[index]); } else { return( null ); } } from service homecoming promise

then in contactcontroller chain 1 more handler set value scope.

contactsservice.getcontact(index).then(function(data) { console.log("data in contactcontroller: " + data); if (data) { $scope.contact = data; } else { console.log("no such index"); } });

but in lastly handler (where set result scope) info object in undefined, though, homecoming object handler in service.

so wrong code - jsfiddle? give thanks you.

thank you.

your issue you're not delegating properly. promises rely on return values. follow correctly of time when you're trying apply delegation you're missing return:

self.handleresult = function (data) { handleresultfunc.call(self, data); };

this in promises means "return undefined immediately" since javascript has implicit undefined returns. instead, should return result:

self.handleresult = function (data) { homecoming handleresultfunc.call(self, data); };

overall - think have avoided issue had used simpler construction in code - i'm not aware of broader design constraints have. alternative - have referenced self via closure , self.handleresult = handleresultfunc have been simpler well.

happy coding.

javascript angularjs promise

No comments:

Post a Comment