0

I need help to get a value of a json for a function and pass this value of the function to the console, but now i'm recive var = undefined, follow the code below, thanks

var Site = {
    baseUrl: "https://www.usereserva.com/",
    visitUrl: "https://cloud-commerce-visit.oracleoutsourcing.com/"
}

var prodAPI = Site.baseUrl + "ccstoreui/v1/products/" + prodId;
var prodId = '0058597';

console.log("============= SCRIPT CALLCAPRODUCT ==============");
console.log("url API: " + prodAPI);
console.log("Id buscada: " + prodId);

var request = require('request');
var price;

function prodPrice() {
    request(Site.baseUrl + "ccstoreui/v1/prices/" + prodId, function (error, response, body) {
        var corpo = JSON.parse(body);
        price = corpo['sale'];
        console.log(price);  // result 169
    });
}
console.log("preço:  " + prodPrice());
console.log("Requisição CALLPRODUCT foi bem sucedida");
console.log("================================================");  
0

2 Answers 2

2

Yes, you are using prodId variable before assigning the value to prodId. This will return error. Here hoisting will take place. Your code will be compiled as

  var Site = {
    baseUrl: "https://www.usereserva.com/",
    visitUrl: "https://cloud-commerce-visit.oracleoutsourcing.com/"
}
var prodId ; 
var prodAPI = Site.baseUrl + "ccstoreui/v1/products/" + prodId; // so here 
// prodId is undefined,thats why error. 
prodId = '0058597';

console.log("============= SCRIPT CALLCAPRODUCT ==============");
console.log("url API: " + prodAPI);
console.log("Id buscada: " + prodId);

var request = require('request');
var price;

function prodPrice() {
    request(Site.baseUrl + "ccstoreui/v1/prices/" + prodId, function (error, response, body) {
        var corpo = JSON.parse(body);
        price = corpo['sale'];
        console.log(price);  // result 169
    });
}
console.log("preço:  " + prodPrice());
console.log("Requisição CALLPRODUCT foi bem sucedida");
console.log("================================================");

initialize and assign the prodId variable first and then use it

var prodId =  "0058597";
var prodAPI = Site.baseUrl + "ccstoreui/v1/products/" + prodId; 

Another one is that you are not returning any value from prodPrice() method and default return is undefined. return the required value from method.

Please read about hoisting in java script. this will help Hoisting

Sign up to request clarification or add additional context in comments.

Comments

0

Use Let or const instead of var to avoid such problems.

https://medium.com/javascript-scene/javascript-es6-var-let-or-const-ba58b8dcde75

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.