promise - design pattern to pass an argument to a jquery deferred task -


trying head around deferred tasks. legit make following function promise? want take action not ajax call has resolved --that premature-- when ui element has been populated data returned ajax call. there's loop in success callback.

function populatecitiesdropdown( state ) {      var dfd = new $.deferred();      // ajax call cities specified state     // ...     // (removed)     // ...      url:  "getcitiesforspecifiedstate?state=" + state,      // ...      }).success ( function ( result, b, c) {          // loop through result data         //  populate cities select element         // resolve when loop finished         dfd.resolve();      });      return dfd.promise();  } 

how pass state parameter populatecitiesdropdown function when using $.when( ... ?

$.when( populatecitiesdropdown ).done( function () ... 

edits (additional background):

there multiple dropdowns need populated data returned multiple ajax calls. each task consists of ajax data fetch , select being populated. if pass ajax call $.when:

              $.when(ajax1, ajax2, ajax3).done( function () { foo() ; }); 

then function foo() executes prematurely, i.e. before select elements populated. ajax calls resolve before code inside success callbacks executes.

when of dropdowns have been populated (which occurs time after of ajax requests have resolved) issue bindmainrecordtoui call.

are looking more complicated this:

$.when( populatecitiesdropdown(xxx) ).done( function () ... 

remember $.when() doesn't take callback function. takes promise. so, have call , execute populatecitiesdropdown function (and can pass arguments want when doing so) , returns promise passed argument $.when(). different .done() or .then() handlers indeed callbacks called promise code @ later time.

also, keep in mind if have 1 promise, there no reason use $.when() can put .done() directly on returned promise.

populatecitiesdropdown(xxx).done(function() {...}); 

the purpose of $.when() in managing multiple promises @ once, not one.


also, there's no reason create new deferred. jquery returning promise ajax call can use one:

function populatecitiesdropdown( state ) {      return $.ajax({...          // ajax call cities specified state     // ...     // (removed)     // ...      url:  "getcitiesforspecifiedstate?state=" + state,      // ...      }).then ( function ( result, b, c) {          // loop through result data         //  populate cities select element         // resolve when loop finished      });  } 

and, should switch .then() instead of .success() .success() deprecated , .then() standard promise way of doing it.


Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -