How to grab value from promise in Nodejs

孤街醉人 提交于 2020-08-10 08:44:12

问题


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.

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

Thanks


回答1:


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

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

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.



来源:https://stackoverflow.com/questions/62522194/how-to-grab-value-from-promise-in-nodejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!