Developer
Developer

Reputation: 4331

JavaScript making queue from requests

I have a function, that requests data from the server and opens a page. And returns a page index. Called - showpage(). Also i have methods - active() ( returns the currently open page index ), next() and previous()

So the next and previous methods under the hood do the showpage() method.

But the problem is when i execute this type of script:

console.log(active());
showpage(9998)
console.log(active());
console.log(next());
console.log(active());

It should output me:

0, 9998 9999 9999

But istead it gives me somethig absolutely wrong. I understand that this is related to the server requests, that are finished earlier - are messing up the result.

So i created a simple fiddle, that shows my problem:

https://jsfiddle.net/xpvt214o/875828/

Here is a small sample:

button.on("click", function(){
    makeRequest("https://jsonplaceholder.typicode.com/photos", 1);
    makeRequest("https://jsonplaceholder.typicode.com/comments", 2);
    makeRequest("https://jsonplaceholder.typicode.com/todos", 3);
    makeRequest("https://jsonplaceholder.typicode.com/albums", 4);
    makeRequest("https://jsonplaceholder.typicode.com/users", 5);
})

function makeRequest(url, id){
    $.ajax({
        url: url,
    })
.done(function( data ) {
    console.log(id);
 });
}

So the output should be:

1, 2, 3, 4, 5

There is no jQuery in the project, here it just added for a quick example

Is there a way to easily make them stand in queue? Somethink similar to SemaphoreSlim in C#?

Upvotes: 2

Views: 4762

Answers (1)

Raj Nandan Sharma
Raj Nandan Sharma

Reputation: 3862

Here is an update coded using recursion to maintain the sequence. We fill an array of requests and then we process them one by one until there are no more

var reqArr= [];

button.on("click", function(){
  reqArr.push({url:"https://jsonplaceholder.typicode.com/photos",v:1});
  reqArr.push({url:"https://jsonplaceholder.typicode.com/comments",v:2});
  reqArr.push({url:"https://jsonplaceholder.typicode.com/todos",v:3});
  reqArr.push({url:"https://jsonplaceholder.typicode.com/albums",v:4});
  reqArr.push({url:"https://jsonplaceholder.typicode.com/users",v:5});
  makeRequest();
})

function makeRequest(){
  if(reqArr.length==0) return;//stop recursion
  var obj=reqArr.shift();

  $.ajax({
    url: obj.url,
  })
  .done(function( data ) {
    console.log(obj.v);
    return makeRequest();
  });
}

Upvotes: 1

Related Questions