سؤال

I'm having some issues with the chaining of deferred objects. So I think that Im missing some understanding. My code is something like follow:

var AJAX_FUNC_CREATE_ALIAS = function(){

    return $.when(ajax_call()).then(function(response){
        // DO something with the response I get to compose an object
        return composed_response;
    });
}


var name = 'Alejandro',
    alias = 'Ali';

$.when(AJAX_FUNC_CREATE_NAME)).then(function(response, status, jqXHR){
        return AJAX_FUNC_CREATE_ALIAS(name);   // <-- Wait correctly
    },function(jqXHR, status, errorThrown){
        return default_response;
}).done(function(artist_response){
    var promise = AJAX_FUNC_CREATE_ALIAS(alias); // <-----  Problematic one
    console.log(promise.state());  // It shows pending state

    return promise;
}).done(function(alias_response){
    $.publish(channel, [alias_response])
});

The execution goes like this:

  • The AJAX_FUNC_CREATE_NAME function start execution. When it finishes it goes to the callback defined inside the then().

  • It executes the AJAX_FUNC_CREATE_ALIAS(name) function. The .done() method is not executed until the AJAX_FUNC_CREATE_ALIAS(name) has finished.

  • It start executing AJAX_FUNC_CREATE_ALIAS(alias); In here it does not wait to get answer from the server. It goes straight to the $.publish(....)

Why?

Update: I have added some code for checking the answer I get from the problematic line. The promise I get back seems to have 'pending state'. From the jquery documentation .done() methods : "Add handlers to be called when the Deferred object is resolved." [http://api.jquery.com/deferred.done/] . If the state is pending... why is the done() method getting it?

هل كانت مفيدة؟

المحلول

then returns a new promise,done doesnt.

If you want to chain tasks use then.that's what you did for the second promise,it only makes sense to do the same for the next one.

It's written right here:

http://api.jquery.com/deferred.then

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top