0

I have a clunky ajax queue that uses setTimeout and a global flag:

var InProgress = false;

function SendAjax(TheParameters) {

  if (InProgress) {
     setTimeout(function () { SendAjax(TheParameters) } , 500) 
  }

  InProgress = true;

  $.ajax({
    ...
    data: TheParameters,
    complete: InProgress = false
  });
}

How can I rewrite this using a queuing mechanism so that the requests trigger one after the other in the order they're received?

1 Answer 1

2

By using then we can chain each request sequentially as they come in.

var previousPromise;

// This actually sends the request
function actualSender(params) {
  return $.ajax(...);
}

// This will make sure that the next request will be fired
// when the previous one finishes.
function SendAjax(TheParameters) {
  if (previousPromise) {
    // Even if the previous request has finished, this will work.
    previousPromise = previousPromise.then(function () {
      return actualSender(TheParameters);
    });
    return previousPromise;
  }

  // first time
  previousPromise = actualSender(TheParameters);
  return previousPromise;
}

I didn't test this but the idea should work

Sign up to request clarification or add additional context in comments.

8 Comments

What happens if there multiple requests that come in simultaneously? Wouldn't an array of queued requests work better?
No, because the promises gets chained.
I'm always amazed by the simplicity of jquery's power. Let me test it and I'll get back.
It's actually promises. ;)
Does that mean that the line previousPromise = previousPromise.then(..) adds a promise to the existing promise?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.