how to simplify or cleanely code nested deferreds

Friday, July 11, 2014

Alright you asynchronous guru's here is a nested deferred call that I am not to sure about:


The idea I have here is to string the deferred's together to return me a list of addresses based on the person id.


I am just wondering if this is a good clean way to do it and of course will it work correctly?


by the way, I am using Dojo AMD 1.7



// get account info that is currently cached
var getAccountInfo = function( self ) {
var deferred = null;
deferred = self.get( Account.prototype.type );
return deferred;
}

// get person if found in account
var getPerson = function( accountInfo ) {
var deferred = new Deferred();
var pid = accountInfo.personId;

var success = function( results ) {
deferred.resolve( results );
};

if( pid !== null ) {
this.get( Person.prototype.type, pid ).then( successs );
}
else
{
deferred.resolve( null );
}

return deferred;
}

// get person address if person has one
var getPersonAddresses = function( person ){
var deferred = new Deferred();

if( person.address && person.address.length ) {
this.get( Address.prototype.type, person.pid )
.then( function( result ) {
deferred.resolve( result );
}
);
}
else {
deferred.resolve( [] );
}
return deferred;
}

// get the customer
var getCustomerAddress = function( self )
{
var deferred = getAccountInfo( self );
.then( lang.hitch( self, getPerson ) )
.then( lang.hitch( self, getPersonAddresses ) )
return deferred;
}

// handle final results
var updateContents = function( results ) {

// do something with results
}





// begin the process by calling getCustomerAddress
getCustomerAddress( this )
.then( updateContents )






http://ift.tt/VTVeqb