Javascript 如何从嵌套函数回调返回值作为父函数的返回值?

Javascript 如何从嵌套函数回调返回值作为父函数的返回值?,javascript,node.js,api,Javascript,Node.js,Api,我有一个名为getClient的函数,它从api接收两个参数,即cloudCreds和type。它使用cloudCreds创建一个名为credentials的参数,客户端调用有一个最内部的回调,该回调接收credentials值,该值反过来用于在类型上使用if-else创建客户端。我的问题是,我需要以某种方式返回这个客户机,作为原始函数(即getClient)的返回值。但是最内部回调的默认范围不允许它。如何重构它,以便轻松地设置和返回客户机。抱歉,如果问题已经被问到,我无法找到解决这个问题的方法

我有一个名为getClient的函数,它从api接收两个参数,即cloudCreds和type。它使用cloudCreds创建一个名为credentials的参数,客户端调用有一个最内部的回调,该回调接收credentials值,该值反过来用于在类型上使用if-else创建客户端。我的问题是,我需要以某种方式返回这个客户机,作为原始函数(即getClient)的返回值。但是最内部回调的默认范围不允许它。如何重构它,以便轻松地设置和返回客户机。抱歉,如果问题已经被问到,我无法找到解决这个问题的方法

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

您必须用回调函数包装函数并解析数据(或拒绝错误)


这回答了你的问题吗?
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)
    })
})