Skip to content

Instantly share code, notes, and snippets.

@chuckbergeron
Created June 9, 2011 16:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chuckbergeron/1017139 to your computer and use it in GitHub Desktop.
Save chuckbergeron/1017139 to your computer and use it in GitHub Desktop.
jQuery Promise / Deferred / AJAX methods in sequence
var Tab = function() {
/*
* EXTRAS
*/
var Extras = function() {
var show = function( id ) {
var extra = $( "#" + id ),
d = $.Deferred();
chained = d;
// If the Extra is a placeholder, gets its content
var div = extra.find( "div:first" );
if ( div.length )
chained = chained.pipe( prepareExtra( div ) );
// Authenticates the user if:
// * the extra requires auth
// * he is not already authenticated
if ( extra.attr( "requires-auth" ) != undefined && !config.user_is_authenticated )
chained = chained.pipe( authenticate );
// When the two optional methods are resolved, show the content
chained.done( function() { extra.fadeIn( 500 ) } );
d.resolve();
};
var prepareExtra = function( div ) {
return $.post( div.attr( "href" ), {}, function( data ) {
div.html( data )
} );
};
}();
var authenticate = function() {
var d = $.Deferred();
FB.ui( { method: "permissions.request", perms: "email" }, function( response ) {
if ( response.session )
$.post( "/authenticated/create_or_log_in_user", {
access_token : response.session.access_token
}, function() {
config.user_is_authenticated = true;
d.resolve();
} ); } );
return d.promise();
};
}();
@atesgoral
Copy link

pipe takes functions, not Promises. Try changing your prepareExtra to:

var prepareExtra = function( div ) {
  return function () {
      return $.post( div.attr( "href" ), {}, function( data ) {
        div.html( data )
      } );
  };
};

So that it returns a function that will be called when the previous Deferred is resolved.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment