如何在Node.js中从Promise中获取价值 [英] How to grab value from promise in Nodejs

查看:411
本文介绍了如何在Node.js中从Promise中获取价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Azure函数中编写Node.js代码,以捕获保存在Azure密钥保管库中的用户名. 这是我写的代码

Hi I am writing a nodejs code in Azure functions to capture the username saved in Azure key vault. Here is the code I have written

module.exports = async function (context, req) {
    var msRestAzure = require('ms-rest-azure');
    var KeyVault = require('azure-keyvault');

    function getKeyVaultCredentials() {
        return msRestAzure.loginWithAppServiceMSI({
        resource: 'https://vault.azure.net/'
     });
    }

    function getKeyVaultSecret(credentials) {
        let keyVaultClient = new KeyVault.KeyVaultClient(credentials);
        return keyVaultClient.getSecret('https://myDNS.vault.azure.net/', 'username', '');
    }


const username = getKeyVaultCredentials()
 .then(getKeyVaultSecret)
 .then(function (secret){
 context.log(`Your secret value is: ${secret.value}.`);
    return secret.value;})
 .catch(function (err) {throw (err);});

context.log(username) 
    context.res = {
        body: username 
    };
}

我想捕获用户名,但这给了我输出

I want to capture the username but it is giving me output as

promise {pending}

如何等待函数结束,以便提取用户名.

How to wait for the function to end so that I can extract the username.

我是一个非常新的nodejs,请让我知道我在做什么错以及应该采取的确切解决方案.

I am very new nodejs, please let me know what wrong I am doing and what should be the exact solution.

谢谢

推荐答案

实际上,您已经使用then来获取机密值.如果相关性和配置没有问题,则将返回该值.

Actually you have already used then to get the secret value. The value will be returned if there is no issues with the dependencies and configurations.

getKeyVaultCredentials()
 .then(getKeyVaultSecret)
 .then(function (secret){
 context.log(`Your secret value is: ${secret.value}.`);
    return secret.value;})
 .catch(function (err) {throw (err);});

但是使用此sdk和此处是github问题,供您参考.

But you will encounter some issues when using this sdk and here is the github issue for your reference.

建议您使用新的 Azure Key Vault SDK 反而.使用起来更方便. 此处是在 MSI Key Vault 中使用的详细步骤Azure功能.

It is recommended that you use the new Azure Key Vault SDK instead. It is more convenient to use. Here are the detailed steps to use MSI and Key vault in Azure function.

这篇关于如何在Node.js中从Promise中获取价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆