skip to Main Content

I am trying to use Promises but I don’t know if in this case, are useful.

$.getJSON("url", "data", function(json) {
    json.forEach(function(item) {
        //do something
        $.get("url", "data", function(response) {
            //MAKE SURE THIS BODY IS SOLVED BEFORE RELOOP???
        });
    })
})

The only way I found is to use ajax with async as false.

Is there a way to solve this?

Maybe using Promises for example? I tried to think a way to use Promises in a foreach loop but didn’t find any solution.

I tried this one:

$.getJSON("url", "data", function(json) {
    json.forEach(function(item) {
        //do something
        when($.get("url", "data") {
            //do something
        })).done(function(response){
            //do something
        });
    })
})

But it doesn’t work. foreach always relooped.

2

Answers


  1. This may be of interest to you… As you wish to perform many ajax request one by one in a loop.

    Using await in an async function, you can wait for an ajax resquest to complete before doing the next one.

    Below, I used $.getJSON in a for loop… And the console logs clearly show that each request where made one by one.

    The $.ajax(), $.post(), $.get(), $.getJSON(), etc. all are returning a promise. So await can be used. Instead of using the callback function, you have to assign the response to a variable.

    as in:

    let response = await $.getJSON(url);
    

    instead of:

    $.getJSON(url, function(response){...});
    

    let url = "https://jsonplaceholder.typicode.com/todos/";
    let max = 40;
    
    async function loop() {
      for (i = 1; i <= max; i++) {
        console.log(`=============================== Loop ${i}`);
        let response = await $.getJSON(url + i);
        console.log(response);
        $("#result").append($("<div>").text(response.title));
        console.log(`request ${i} is finished`);
      }
    }
    
    loop();
    

    — That is working in CodePen since the SO snippets are squarely blocking any ajax request.

    Login or Signup to reply.
  2. As an alternative, you could try re-constructing your data from outer-call to build an array and make use of a function to reflect the looping mechanism and initiate each iteration when the previous inner-call finishes (successfully or not).

    Check this out. Might this be a viable solution for you?

    $.getJSON("url", "data", function(json) 
    {
        var jarray=[];
        var i=0;
        for (var xitem in jsonObj) { 
            //console.log(jsonObj[xitem]);      
            jarray[i++]=jsonObj[xitem];
        }
        nextIteration(jarray,0);
    })
    
    function nextIteration(sourceArray, nextIterationIndex)
    {
        if(nextIterationIndex<sourceArray.length)
        {
             var item = sourceArray[nextIterationIndex];
                //do something
                $.get("url", "data", function(response) 
                {
                    //MAKE SURE THIS BODY IS SOLVED BEFORE RELOOP???
                    nextIteration(sourceArray,nextIterationIndex+1);
                });
             
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search