0

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)
     }

   };
  • Possible duplicate of [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – zero298 Aug 15 '18 at 20:47
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Sebastian Simon Aug 15 '18 at 20:56
  • Thanks- these are helpful but I'm still unsure where I should put the callback. I've edited the original post for more info – anderscodes Aug 15 '18 at 22:44

0 Answers0