0

I am getting output as undefined in the last line of code. Ideally it should print the value of cost variable which I have assigned in the last line of call function . cost variable is printing value correctly. what mistake I am making. or how can I access value of cost outside the function.

var request = require("request");
 var itemCost;

 function call() {

   request.get("http://localhost:8080/ords/hr/rest-v3/item/Sugar", (error, response, body) => {

            if (error) {
                return console.dir(error);
            }
            let jsonData = JSON.parse(response.body);
            let obj = new Object(jsonData);

            obj.items.forEach(itemChild => {
                let cost = itemChild.itemcost;
                console.log(cost);
                itemCost = cost;  //Assigning value of cost to itemcost. is this correct way?
            })

        });
    }

    call();
    console.log(itemCost); //here I am getting undefined. I want value of cost here.
str
  • 42,689
  • 17
  • 109
  • 127
  • 2
    of course? `request.get` is asynchronous, so it gets called, gets scheduled for resolution at some later time, your code _immediately_ continues to `call()` and `console.log`, and by the time `itemCost` actually gets set, the rest of your code is done already: don't console.log a value until you have that value (e.g. put your console log alongside the same code that _sets_ itemCost) – Mike 'Pomax' Kamermans Mar 24 '20 at 17:44
  • Basically I have to access that value in some other function. is there any way to do that? –  Mar 24 '20 at 17:47

1 Answers1

0

So request.get is asynchronous, you have to log that itemCost inside your callback otherwise you need to chain your operation with Promises(here is an example) or sth.

Its undefined because console.log(itemCost); doesn't actually wait for request.get to get finished so the itemCost is not calculated until you reach to that line.

Basically I have to access that value in some other function. is there any way to do that?

You can call the function inside your callback by just passing the itemCost variable. For example

request.get("http://localhost:8080/ords/hr/rest-v3/item/Sugar", (error, response, body) => {

    if (error) {
        return console.dir(error);
    }
    let jsonData = JSON.parse(response.body);
    let obj = new Object(jsonData);

    obj.items.forEach(itemChild => {
       let cost = itemChild.itemcost;
       console.log(cost);
       itemCost = cost;  //Assigning value of cost to itemcost. is this correct way?
    })

    foo(itemCost); //call the method you need by passing the calculated variable

     });
    }
Alexis Pavlidis
  • 1,080
  • 1
  • 11
  • 21