首页 > 解决方案 > 如何从嵌套函数回调中返回一个值作为父函数的返回值?

问题描述

我有一个名为 getClient 的函数,它接收两个参数,即 cloudCreds 和来自 api 的类型。它使用 cloudCreds 创建一个名为 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
};

标签: javascriptnode.jsapi

解决方案


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

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

推荐阅读