1

a today, i´m learning lightning, and i block with asyncronous callback. To practice, i did a small helper with apex call and a callback, but when a update a var out of callback, the value in callback changes. My code is:

getTestList: function (cmp) {
    var action = cmp.get('c.getTestList');
    var counter
    for (counter = 0; counter <= 5; counter+=1) {
        action.setCallback(this, function (response) {
            var state = response.getState();
            if (state === 'SUCCESS') {
                // do something
            }
            console.log(counter);
        });
        $A.enqueueAction(action);
    }
}

Thanks.

0

1 Answer 1

0

The issue I see with this is that your accessing the variable when the callback is called, not when the callback is written. Since this is asynchronous, the function you are defining as the callback is accessing the counter variable after all 5 instances of the action have been en-queued so counter would be 5 in all callbacks..

Passing extra data to a callback does not seem possible to me as you are not the one calling the method. Your method gets what ever parameters are passed to it by the action.setCallback method. In this instance, you get the response object.

My recommendation is move the for loop containing the counter to the apex side of the equation; if possible. Send the list to the apex controller rather than looping through a list of data and en-queuing the action 5 times. Have the controller loop through the records and return a set of results that you can loop through in the JavaScript.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .