1

I'm trying to make a request to this MailGun endpoint. I need this function to return an AcessResponse object but I having trouble returning the response before my function gets to return {data: {info: "Bad test"}}. How do I wait to return anything until my request finishes? I've tried not including a return statement at the end of this function but then it errors saying I need to return something. TIA.

access: async (identifier: string): Promise<AccessResponse> => {

    var options = {
      url: 'https://api.mailgun.net/v3/lists/pages',
      auth: {
          'user': 'api',
          'pass': '*********************************'
      }
  };
  
  function callback(error, response, body) {
      if (!error && response.statusCode == 200) {
          console.log(body);
          return {data: response.body}; 
      } 
    }
    request(options, callback);
    return {data: {info: "Bad test"}}
  },
VLAZ
  • 26,331
  • 9
  • 49
  • 67
acohen89
  • 83
  • 1
  • 4
  • 2
    You can't. `request()` is asynchronous and non-blocking. It will return from the `request()` call long before it calls the callback. And, our function itself will return before the callback gets called. If you're trying to communicate back some result from the call to `request()`, then see [How to return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call/14220323#14220323). – jfriend00 Feb 21 '22 at 17:06

0 Answers0