0

I have two modules and in the first one I declare an object because I know that primitives are passed by value in java script and objects by reference.I want to get the response status from a request and I am passing the object as a reference so I will be able to modify its property.The problem is that it doesn't do anything.In the end the value would be the same.

//this code is in a different module from the other one
var variableToBeChanged = { something : "Initial value" };
anotherModule.changeValue(variableToBeChanged);
alert(variableToBeChanged.something);

//and in the other module I have a $.ajax and I want to get the response status(ex. 200)

//the code is sth like this:

function AnotherModule(ajax){

  function changeValue(variableToBeChanged){
    ...
    ...
    ...
    $.ajax({
      ...
      ...
      ...
      success: function(data,xhr){
          variableTobechanged.something = xhr.status;
      }
    });
  }

}

In the end it will display: "Initial value" instead of 200 or anything else. What am I doing wrong here?

Bogdan V
  • 13
  • 5

2 Answers2

1

The ajax call is asynchronous and therefore the alert gets called before the variable is modified. You can use promise in ES6 like this to make sure it is executed after ajax call completes.

    new Promise((resolve) =>{ 
             anotherModule.changeValue(variableToBeChanged);
             resolve();
        }).then((res) =>{
            alert(variableToBeChanged.something);
        }).catch((error) =>{
            alert(error);
    });
Rohit Agrawal
  • 1,496
  • 9
  • 20
  • In your case, you may also consider returning the deferred object that ajax() returns and using the done or fail methods on it, as you seem to be interested whether the call succeeds or fails ourside of your module. [See The jqXHR Object](http://api.jquery.com/jquery.ajax/). – Stefan Oct 06 '17 at 06:38
  • Hi @Stefan, yes we can return an object from ajax call in case of success or failure and resolve or reject promise accordingly. – Rohit Agrawal Oct 06 '17 at 06:43
  • Thank you for your comment! I have one question: Is it bad practice to use jQuery.ajaxSetup({ async : false} ) and jQuery.ajaxSetup({ async : true} ? – Bogdan V Oct 06 '17 at 14:03
0

In javascript copy of reference to object is passed.

This means that any changes made to the object will be visible to you after the function is done executing.

Since javascript is asynchronous , alert(variableToBeChanged.something) this line gets executed before your function returns . Therefore you see old value . You have to use callbacks or promise to work synchronously.

Please refer to this question javascript pass object as reference .It explains this concept beautifully.

vertika
  • 1,284
  • 1
  • 8
  • 22