javascript - 如何从嵌套函数回调中返回一个值作为父函数的返回值?
问题描述
我有一个名为 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
};
解决方案
您必须用回调包装函数到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)
})
})
推荐阅读
- python - 如何使用 np.where 或列表推导创建子字符串掩码?
- reactjs - 用数组反应 useState 钩子
- python - 运行大量使用 Python 多处理修改同一列表的进程会导致 OSError:打开的文件过多
- javascript - 在Javascript中为每个嵌套的孩子添加父ID
- c# - 当新创建的窗口出现异常时,C# WPF 应用程序在退出后继续运行
- mule - 我们如何在 MULE 中的 VM 连接器中存储失败的消息
- javascript - 在 react App 中的 history.goBack() 之后获取新路径名
- tuples - 功能类似于 CoreNLP 在 spaCy 上的 OpenIE
- sql - 以最接近的匹配时间执行 JOIN
- node.js - 如何在不降低性能的情况下在 ReactJs 和 NodeJs 中有效地运行非常大的计算?