steo
steo

Reputation: 4656

Make an AJAX queue to resolve request later

I'm looking at Deferred object in jQuery. What I'm thinking about is how to make a queue of request that are called before a particular request , but should be resolved only after this last one.

I explain :

I am inserting tags . Every time I insert a tag, I should insert it into a database through an AJAX request. To make this AJAX request I need an id that is generated by another AJAX request that I will call later.

I think it can be resolved through .promise() but I didn't understand how is it working.

Here is an example in pseudo-code of what I am trying to achieve :

ajaxReq(id) //is called every time I insert a tag
generateId() //this generate the id a need

when generateId is called -> ajaxReq is resolved (even if i "called" it before)

Upvotes: 0

Views: 248

Answers (2)

Alnitak
Alnitak

Reputation: 339906

It does appear that your information flow is incorrect. You simply cannot make the "first" AJAX request until the second one has been completed and assigned the ID.

In essence, you just need a local list of tags that are waiting to be submitted:

var tags = [];

and a way to add tags to the list:

// Add a new tag to the queue
function makeTag() {
    tags.push(...);
}

in which you can execute any code immediately that doesn't depend on the value of id.

Some time later, some event will cause the "commit" of this information. You'll need to get an ID:

function generateID() {
    return $.ajax(...);
}

and you'll need a function to process that ID and actually commit your data to the database, in this case making an AJAX call per tag:

function commitOneTag(id, tag) {
    return $.ajax(...);   
}

function commitTags(id) {
    return (function loop() {
        var tag = tags.shift();
        if (tag) {
            return commitOneTag(id, tag).then(loop);
        }
    })();
}

and then a way to chain it all together:

makeTag();
makeTag();

generateID().then(commitTags).done(function() {
    // processing will continue here once the entire
    // AJAX chain has been completed
 });

This is using .then to allow "chaining" of promises.

See http://jsfiddle.net/alnitak/5BHXt/ for a worked example

Upvotes: 3

face
face

Reputation: 1505

Wow! I am looking at the promise() method for the very first time and I am already impressed. For your logic I think a psuedo code can be written like this:

$(document).ready(function(){
var myDeferredObj = $.Deferred();
var ajaxReq = function(){
    // Initial part of logic that does not need id
    alert('here');
    myDeferredObj.promise().done(function(args1, args2) {
        alert(args1 + ':' + args2);
        // Use id provided by generateID
    });
};

var generateID = function(){
    //get ID
    id = 5;//suppose
    alert('generate');
    myDeferredObj.resolveWith(this, [id, id]);
}

ajaxReq();
generateID();
});

This works fine for me! Fiddle - http://jsfiddle.net/569LL/

Upvotes: 2

Related Questions