0

I have a function called getClient which receives two parameters i.e cloudCreds and type from an api. It uses the cloudCreds to create a parameter called credentials and the client call has an innermost callback which receives the credentials value, which in turn is used to create the client using if-else on the type. My issue is that I need to somehow return this client as the return value for the original function i.e getClient. But the default scope of the innermost callback won't allow it. How can I refactor this so that the client is set and returned easily. Apologies if the question is already asked I was unable to find a solution for this exact problem.

const getClient = async (cloudCreds, type) => {
  const { SubscriptionID, ClientID, ClientSecret, TenantID } = cloudCreds;
  msRestAzure.loginWithServicePrincipalSecret(ClientID, ClientSecret, TenantID,
    (err, credentials) => {
      var client;
      if (type === "compute") {
        client = new ComputeManagementClient(credentials, SubscriptionID);
      } 
      else if (type === "network") {
        client = new NetworkManagementClient(credentials, SubscriptionID);
      } 
      else if (type === "storage") {
        client = new StorageManagementClient(credentials, SubscriptionID);
      } 
      else {
        client = new ResourceManagementClient(credentials, SubscriptionID);
      }
    }
  );
  return client; //this needs to be returned
};
shivam aima
  • 103
  • 5
  • 12
  • 1
    Does this answer your question? [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) – eol Sep 22 '20 at 14:14

1 Answers1

0

You have to wrap function with callback to Promise and resolve data (or reject errors)

const getClient = async (cloudCreds, type) => new Promise((resolve, reject) => {
const {
    SubscriptionID, ClientID, ClientSecret, TenantID
} = cloudCreds;
return msRestAzure.loginWithServicePrincipalSecret(ClientID, ClientSecret, TenantID,
    (err, credentials) => {
        if (err) {
            return reject(err)
        }
        let client;
        switch (type) {
            case 'compute':
                client = new ComputeManagementClient(credentials, SubscriptionID);
                break;
            case 'network':
                client = new NetworkManagementClient(credentials, SubscriptionID);
                break;
            case 'storage':
                client = new StorageManagementClient(credentials, SubscriptionID);
                break;
            default:
                client = new ResourceManagementClient(credentials, SubscriptionID);
                break;
        }
        return resolve(client)
    })
})
l2ysho
  • 2,542
  • 1
  • 20
  • 41