Reputation: 365
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("================================================");
Upvotes: 0
Views: 67
Reputation: 556
Use Let or const instead of var to avoid such problems.
https://medium.com/javascript-scene/javascript-es6-var-let-or-const-ba58b8dcde75
Upvotes: 0
Reputation: 799
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
Upvotes: 2