0

I have a call to a externa function getUsers. This function perform a request to an API and based on the retrieved info must return a value that has to be readable by the original function caller:

Original call

library.getUsers( params )

getusers method

{
   headers = ...
   options = ...

   function callback ( error, response, body ) {

      if ( all is correct ) { 
      
      // here I need to return a true

      }

   }
request( options, callback )
}

I need to get that "true" on the original call, but I only receive undefined. I also tried to make the return outside the callback but of course because it's async it doesnt return that true either.

Javier Ortega
  • 147
  • 10

1 Answers1

-1

You can use Promise for this.

function getUsers(params) {
  return new Promise((resolve, reject) => {
    headers = ...
    options = ...
    
    request(options, (error, response, body) => {
      if (error) {
        reject(error);
        return;
      }
      if ( all is correct ) { 
        // here I need to return a true
        resolve(true);
        return;
      }
      
      resolve(false);
    });
  });
}

library.getUsers(params)
  .then((value) => {
    // You can get the result of getUsers (true or false) here for `resolve(...)`
  })
  .catch((error) => {
    // Can be reached here when the function throwed error for `reject(...)`
  });
Derek Wang
  • 10,098
  • 4
  • 18
  • 39