user6815795
user6815795

Reputation:

Call a function inside jquery each

I have a jquery each function.Inside it i am calling a function.The function inside the each should be called only if this function is completed for the previous element.

function x(t){
    var a = something;

    $.each(a, function(index,value){
        y(this);
    });
}

function y(t){
    $.ajax({

    }).done(function(r){
        if(r.success){                 
                     }
        else{
        }

     });

    // This function should be called for the second element 
    // in the each function only if its completed for the first element.
}

Upvotes: 2

Views: 2988

Answers (2)

Justinas
Justinas

Reputation: 43441

$.each is synchronous function, so next iteration only happens when current one is done (including calling and executing y(this), unless inside there is async actions)


To do it using Ajax:
Use imitation of loop using recursion.

var currentIndex = 0;

function x(t) {
    if (currentIndex >= something.length) {
        return;
    }

    $.ajax({
       url: '',
       data: something[currentIndex],
       success: function () {
           currentIndex++;

           x(t);
       }
    });
}

Upvotes: 5

Jordi Flores
Jordi Flores

Reputation: 2150

As said above by others, this function runs synchronously, so, when item 2 arrives it's already done by item 1.

Here's and example, but otherwise is the fact that the y function runs something async, but you didn't specify that no?

function x(t){
    var a = ["one", "two", "tree"];

    $.each(a, function(index,value){
        y(this, index);
    });
}

function y(t, index){
    // This function should be called for the second element 
    // in the each function only if its completed for the first element.
    console.log(index + " "+ t +" => running in y")
}
x("")
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 1

Related Questions