Tuesday, 15 January 2013

ajax - Is this actually a js promise? -



ajax - Is this actually a js promise? -

i have code in javascript module (i'm using require js , knockout)

var getpersons = function(personsobservable) { personsobservable([]); var getoptions = { url: 'api/persons', type: 'get', datatype: 'json' }; homecoming $.ajax(getoptions) .then(querysucceeded) .fail(queryfailed); function querysucceeded(data) { var persons = []; data.sort(sortpersons); data.foreach(function (item) { var p = new model.person(item); persons.push(p); }); personsobservable(persons); }; }

and in 1 using module phone call this:

function refresh() { homecoming dataservice.getpersons(persons).then(dataservice.gettalks(talks)); };

being gettalks function in dataservice module.

but i'm not sure if result of actual promise, i.e. until populate persons result of ajax phone call gettalks won't invoked. far understood calling method trick, right?

thanks

update:

so after reading answers , farther investigating these promises stuff came this, don't know if makes sense

now getpersons , gettalks don't populate observable homecoming arrays, , refresh function looks this:

function refresh() { homecoming $.when(dataservice.getpersons(persons), dataservice.gettalks(talks)) .then( //success function (personargs, talksargs) { persons(personargs); talks(talksargs); }, //failure function(){ logger.log("there's been error retrieving data"); }); };

ti still need refresh returns promise, still doubting it.

if function getpersons named, (get persons) , no more, , 2 calls personsobservable made @ point getpersons called.

getpersons compact downwards :

var getpersons = function () { homecoming $.ajax({//return here create make result of $.ajax().then() chain available @ point getpersons() called. url: 'api/persons', datatype: 'json' }).then(function (data) { //sortpersons presumably defined in outer scope homecoming data.sort(sortpersons).map(function (item) {//return here create mapped array available promised result of getpersons. homecoming new model.person(item);//return here force elements onto mapped array }); }); };

note - maintain things clean , efficient, no assignments made within function

and called, example, follows :

persons([]); getpersons().then(persons).fail(queryfailed);

the entire promise chain (in shorthand) $.ajax().then().then().fail();, split such first 2 calls in chain within getpersons, returns appropriate promise.

the utilize of $.when() in refresh function makes things more complicated. gettalks modified in same way getpersons, refresh written follows :

function refresh () { persons([]); talks([]);//assumed homecoming $.when(dataservice.getpersons(), dataservice.gettalks()).then(function (p, t) { persons(p); talks(t); }, function () { logger.log("there's been error retrieving data"); }); };

ajax promise knockout-2.0

No comments:

Post a Comment