1

I want my function to process the results, then call itself from the done callback.

function geocode(id) {
    console.log(id + ' geocode');
    $.ajax({
        url: '/customers/' + id + '/geocode',
        dataType: 'json',
        data: {
            id: id,
        }
    }).done(function() {
        var newID = id++;
        console.log(id + ' done.');
        geocode(newID);
    });
}

This isn't incrementing though, say if I start it at 1, it just loops on 2 forever. I know it's a pain returning data from ajax, but I've never fully got my head round the nuances

1
  • what do you exactly want? you want response from the ajax request..? Commented Jan 25, 2016 at 13:44

2 Answers 2

3

You need to increment the variable before you set it to the value of newId:

function geocode(id) {
    console.log(id + ' geocode');
    $.ajax({
        url: '/customers/' + id + '/geocode',
        dataType: 'json',
        data: {
            id: id,
        }
    }).done(function() {
        console.log(id + ' done.'); // show this before incrementing
        var newID = ++id; // note the operator order here
        geocode(newID);
    });
}

Working example

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

7 Comments

Does he not need a context?
Possibly, depending on the scope of id and it's use elsewhere in code that isn't shown here.
@mplungjan Why, the correct context is set as i can see it
This works perfectly. I need to look into the operators a bit more, I didn't realise there would be a difference between i++ and ++i
console.log(id + ' done.'); should be set before pre incrementation to get older value
|
-1

Your id will be 1 on the first iteration, and 1 on the second (and third, fourth etc.) iteration as well as you never update it's value.

Try this:

function geocode(id) {
    console.log(id + ' geocode');
    $.ajax({
        url: '/customers/' + id + '/geocode',
        dataType: 'json',
        data: {
            id: id,
        }
    }).done(function() {
        id = id++;
        console.log(id + ' done.');
        geocode(id);
    });
}

1 Comment

This is logically the same as what the OP currently has.

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.