Simply create a variable outside the callback and assign it inside the callback result
var id
const options = {
***
},
};
request(options, function(error, response, issue) {
const json = JSON.parse(issue);
for (let i = 0; i < json.versions.length; i++) {
const test = json.versions[i].name;
if (test === version) {
id = json.versions[i].id; // here id is the id we declared in line 1.
}
}
});
console.log(id);
The value of id
is going to be undefined at console.log(id);
because the http request has not yet executed completely. You can either use callbacks, or a promise or a setInterval for id to be defined.
Using setInterval
var id
const options = {
***
},
};
request(options, function(error, response, issue) {
const json = JSON.parse(issue);
for (let i = 0; i < json.versions.length; i++) {
const test = json.versions[i].name;
if (test === version) {
id = json.versions[i].id; // here id is the id we declared in line 1.
}
}
});
var _interval = setInterval(() => {
if(id !== undefined) {
console.log(id);
// clearing interval
clearInterval(_interval)
}
}, 1000)
Using promise
below is an example of how to convert your request into a promise and then use the id
const options = {};
const promised_request = () => new Promise((resolve, reject) => {
request(options, function (error, response, issue) {
if (error) {
return reject(error);
}
const json = JSON.parse(issue);
for (let i = 0; i < json.versions.length; i++) {
const test = json.versions[i].name;
if (test === version) {
const id = json.versions[i].id;
return resolve(id);
}
}
});
});
promised_request().then((id) => {
// use your id here
console.log(id);
});