I'm writing a Node js program that will create a value by making an API call. and the program is as below.
request(postData, function (error, resp, body) {
console.log("Status code " + resp.statusCode);
if (!error && (resp.statusCode == 200 || resp.statusCode == 201)) {
var z = "";
if (body) {
var x = JSON.parse(body);
for (var i = 0; i <= 5; i++) {
getTheDealerDetails(x.results[i].place_id, function (data) {
var x1 = JSON.parse(data);
if (data) {
console.log(x1.result.name);
z += x1.result.name
}
});
}
console.log("From inner " + z);
} else {
console.log("I am unable to authenticate you. please disable the skill and re link your account");
callback("I am unable to authenticate you. please disable the skill and re link your account");
}
} else {
console.log(error);
callback(error);
}
});
function getTheDealerDetails(paceId, callback) {
var postData = {
uri: "https://maps.googleapis.com/maps/api/place/details/json?placeid=" + paceId + "&key=myKey",
method: "GET",
};
request(postData, function (error, resp, body) {
if (!error && (resp.statusCode == 200 || resp.statusCode == 201)) {
if (body) {
var x1 = JSON.parse(body);
callback(body);
} else {
console.log("I am unable to authenticate you. please disable the skill and re link your account");
callback("I am unable to authenticate you. please disable the skill and re link your account");
}
} else {
console.log(error);
callback(error);
}
});
}
Here I want to assign the result to z
and when I run my above program, z is printing nothing. but, x1.result.name
is printing the exact value.
This is very confusing, can someone please let me know where am I going wrong and how can I fix this.
Thanks