-2

Here is a sample code

function() {
    var test = 0;
    var url = 'http://test.php';
    var user_id = 1;
    $http.post(url,{user_id: user_id})
    .then(function (response){ 
         test = response.something;
    })
    console.log(test)
}

It returns the value 0. I need it to return response.something.

Chowder
  • 51
  • 2
  • 11
  • You have to wait the promise to be resolved. See a similar situation here: http://stackoverflow.com/questions/43259349/how-to-access-a-returned-result-outside-the-then-in-javascript-angularjs/ – lealceldeiro Apr 06 '17 at 16:09

2 Answers2

2

You're not invoking the function calling test = 1

You can wrap the inner function within an IIFE

function() {
    var test = 0;
    (function(){
        test = 1;
    })() // Call the expression immediately
    console.log(test)
}

Edit for Question Update

The console.log(test) is happening before the promise from $http.post() resolves, you need to move the console.log() within your then() callback.

function() {
    var test = 0;
    var url = 'http://test.php';
    var user_id = 1;
    $http.post(url,{user_id: user_id})
    .then(function (response){ 
         test = response.something;
         console.log(test) // Move console.log inside promise then
    })

}
peteb
  • 18,552
  • 9
  • 50
  • 62
0

It's because $http.post is an asynchronous method call. By the time your code gets to the console.log call at runtime, the data from $http.post may not have returned yet, therefore it would log the old value and not the new one.

If you want to console.log the value after the post request has returned, you should move the console.log statement to the then block which will only run after the call has been returned.

function() {
    var test = 0;
    var url = 'http://test.php';
    var user_id = 1;
    $http.post(url,{user_id: user_id})
    .then(function (response){ 
         test = response.something;
         console.log(test) // Move console.log inside promise then
    })

}

If that does not work for you, it is because your call is likely failing for some reason or another. In this case, you can provide an additional function to handle the error.

function() {
    var test = 0;
    var url = 'http://test.php';
    var user_id = 1;
    $http.post(url,{user_id: user_id})
    .then(function (response){ 
         test = response.something;
         console.log(test) // Move console.log inside promise then
    }, function(err) {
       test = err;
       console.log(test)
    });
   }
Pytth
  • 4,008
  • 24
  • 29