I am using https to get the json from the api . I want to store this json in an array .
function getName(code){
Var result = [];
Https.get(apiroute,res=>{
res.on("data",chunk=>{
Var parsedJSON = JSON.parse(chunk);
result.push(parsedJSON.data);
});
});
return result;
}
But when I try to access result array it's empty .
CodePudding user response:
It's most likely empty because as JS is async, you're accessing results before anything has actually been added in.
Use async functions to await for the HTTPS request to have completed before continuing with that part of the code. An example of how the getName function can look as a promise is
function getName(code) {
return new Promise((resolve, reject) => {
var result = []
let req = https.request(apiroute);
req.on('data', chunk => {
var parsedJSON = JSON.parse(chunk);
result.push(parsedJSON.data);
resolve(res);
});
req.on('error', err => {
reject(err);
});
});
}