-1

I have defined a function by using let and then created a function. This function send a post request to an api and get data in json format. In this function I have used a variable and set it equal to the value of the response.

when I use this function all works fine. whenI use this variable outside the function then I get undefined value''

below is my code

var request = require("request");

let conkey = 'Some Value', //varialble for consumer_key
consec = 'Some Value', //varialble for  consumer_secret
tkn = 'Some Value', //varialble for token
tknsec = 'Some Value',
value;


function myFunction() {
request.post('someurl', {
    oauth: {
        consumer_key: conkey,
        consumer_secret: consec,
        token: tkn,
        token_secret: tknsec
    },body: {"skillIds": [some value]
},json: true}, function (err, res, body) {
    if (err) throw new Error(err);
    value = body.sonething.something;
    console.log(value);  ////THIS WORKS FINE
});
};

myFunction();
console.log(value);  ////This prints Undefined
creativated
  • 211
  • 3
  • 16
  • 2
    And I'd imagine that you're getting `undefined` in console **before** the one that works. You may want to read this: [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Tyler Roper Feb 17 '19 at 04:15
  • Could you post code that actually reproduces the issue? – P Varga Feb 17 '19 at 04:19

3 Answers3

1

This occurs because request.post is an asynchronous action. Which means it is going to be completed eventually but not immediately. That is also why request.post accepts a function, which is known as the callback function.

function (err, res, body) { ... } will be called only when the request finishes.

Let's walk through your code in order... it will first:

1 - Create your variables.

2 - Define myFunction

3 - Calls myFunction. myFunction will call on request.post. However request.post is asynchronous. This means it will return immediately before it has the result. myFunction now exits.

4 - console.log(value); is now called, but at this point of time, value is undefined.

5 - When the request is completed, function (err, res, body) (defined in the request.post call) will execute

value = body.sonething.something;
console.log(value);

And value here will now be defined.

Hope this helps.

Norman Breau
  • 2,132
  • 16
  • 35
0

You may try to use js’s fetch api, which is promise based, it will help you solve your issue. Or some other side libraries, such as axios.

The problem is that your code doesn’t wait for request to be received and console.logs before your response would change Value’s “value”. That’s why I think you get undefined.

Sth
  • 522
  • 8
  • 21
0

Thanks everyone for your answers. I was able to get over the issue by creating an empty object outside the function and with in function I inserted the values in the empty object.

creativated
  • 211
  • 3
  • 16