1

How can I update this javascript array using JS Remoting?

var data = [];

Visualforce.remoting.Manager.invokeAction('{$RemoteAction.myController.myMethod}',
    function(result, event) {
        if (event.status) {
            for (var i=0; i<result.length; i++) {
                 data.push({myKey: result[i].fieldName});
            }
            console.log(data);
        } else {
            alret(event.message)
        }
    },
    {escape: true}
);

console.log(Array.isArray(data));
console.log(data);
console.log(data.length);
console.log(data[1].myKey);

Apex controller is supposed to return 4 records, so as expected, from inside invokeAction, javascript console print out this.

enter image description here

But after it passes through invokeAction, I got these from the last four lines of codes above.

enter image description here

Any idea? Thanks.

1
  • Sang Jung, am sure my answer helps. Please mark it as accepted so that we can close the question.
    – Praveen
    Commented Jul 17, 2016 at 18:58

1 Answer 1

4

RemoteAction callback is asynchronous, invoked by the client(browser) when the server returns the response.

So the javascript as soon as executes remote action call, it proceeds to the next part of the code to be executed, without waiting for the server to send an response.

Below is what is happening :

var data = []; // run and moves to next line

    // executes moves to next without waiting for response from the server
Visualforce.remoting.Manager.invokeAction('{$RemoteAction.myController.myMethod}',
        function(result, event) {
            if (event.status) {
                for (var i=0; i<result.length; i++) {
                     data.push({myKey: result[i].fieldName});
                }
                console.log(data);
                console.log(data[1].myKey); // this will work
            } else {
                alret(event.message)
            }
        },
        {escape: true}
    );

// runs and moves to next
console.log(Array.isArray(data)); 

// runs and moves to next, console will display data is empty(initially),
// once the response updates it, data has value in it.
console.log(data); 

// runs and at this time data is empty(no response from server yet)
console.log(data.length); 

// runs and your trying to acesss non-existent element's property data[1] => undefined
console.log(data[1].myKey); //so error!!!!!
1
  • Thanks. I totally missed that remote action is always async.
    – Sang-Jung
    Commented Jul 18, 2016 at 1:20

You must log in to answer this question.

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