I'm fairly new to JavaScript and api calls and I've been struggling to return an array of values from an api call. My code is as follows:
module.exports = function api() {
const array = []
function loop(result) {
const array2 = [];
for (let i = 0; i < result.length; i++) {
array2.push(result[i].id);
}
return array2;
}
request(options, async (error, response, body) => {
if (error) throw new Error(error);
const result = body.results[0].results;
const loop2 = await loop(result);
array.push(loop2);
console.log(array)
});
return array
};
So all I'm trying to do is return the array after the API request has pushed the results to the array.
When I console.log the array within the request I can see the correct response but I can't work out how to return the array after the request has been completed.
I have tried turning the module into an async function and awaiting the request but that has the same effect.
Edit -- after reading some of the comments I think I should be more specific about the issue. I'm not sure how to implement a callback with the request above. I've tried the following but it doesn't seem to work.
module.exports = function api() {
function loop(result) {
const array2 = [];
for (let i = 0; i < result.length; i++) {
array2.push(result[i].id);
}
return array2;
}
request(options, request1(error, response, body, requestResponse));
async function request1(error, response, body, callback){
if (error) throw new Error(error);
const result = body.results[0].results;
const loop2 = await loop(result);
callback();
}
function requestResponse() {
console.log(loop2)
}
};