-1

I used request to get some infromation from API in nodejs. When i try to access these values outside braces it gives undefined.

var tab_det;
    request.post({url:'https://ludochallenge.com/index.php/admin/get_table_id', form: {tournament_id:tournament_id}}, function(err,httpResponse,bodyy){ 
        tab_det = bodyy
        console.log('1 : ' + bodyy);
     }); 
     console.log('2 : ' + tab_det);

Result

1 : {"table_id":"2","player_turn":1}

2 : undefined

please help, Thanks in advance

Rahul
  • 1
  • 1
  • 6
  • See https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – Explosion Pills Aug 09 '18 at 13:02
  • 1
    [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) should be a little closer to the question – Lucas S. Aug 09 '18 at 13:04
  • when you run `console.log('2 : ' + tab_det);` the response has not been returned from the query yet so is undefined. Its part of the asynchronous nature of JavaScript. Please check Luca's linked question – Craicerjack Aug 09 '18 at 13:05

1 Answers1

0

When the thread reaches console.log('2 : ' + tab_det) It's undefined, because value comes from the ajax call:

request.post({url:'https://ludochallenge.com/index.php/admin/get_table_id', form: {tournament_id:tournament_id}}, function(err,httpResponse,bodyy){ 
        tab_det = bodyy
        console.log('1 : ' + bodyy);
     }); 

And response from ajax is reached after the line console.log('2 : ' + tab_det)

Luca Kiebel
  • 9,790
  • 7
  • 29
  • 44
IsraGab
  • 4,819
  • 3
  • 27
  • 46