How to wait till I get the secret values from Keyvault in Node JS?

Viewed 25

I am fairly new to Javascript and I understand that it executes asynchronously. I tried using the callback method to fetch the secret values and then execute next block of code. But it is not waiting. This is the function that fetches the keyvault secret values

function getsecret_values(client,secret_name,callback) {
  let val = []
  for (let i =0;i<secret_name.length;i++){
    client.getSecret(secret_name[i]).then((latestSecret) => {
      val[i] = latestSecret.value;
    })
  }
  callback(val)  
}

I am calling getsecret_values function from main block

let vaultName = result.database;
const url = `https://${vaultName}.vault.azure.net`;
const credential = new ClientSecretCredential(result.host, result.user, result.password);
const client = new SecretClient(url, credential);
let secret_values = []
getsecret_values(client, secrets, function(result) {
    secret_values = result
    console.log(secret_values)
    });
    console.log(secret_values)

\\next code block

Both the console.log returns empty array.

I want my code to wait till the secret values are fetched and put into secret_values array and then proceed to next block of code. How do I achieve this?

1 Answers

the easiest way is to use Async Await pattern, which uses promises in the background. Trying not to change your code much:

async function getsecret_values(client,secret_name) {
  let val = []
  for (let i =0;i<secret_name.length;i++){
    const latestSecret = await client.getSecret(secret_name[i])
    val[i] = latestSecret.value;
  }
  return val  
}

in your main block:

getsecret_values(client, secrets).then(function(result) {
    secret_values = result
    console.log(secret_values)
});

console.log(secret_values) // will still be an empty array as the then function has not been executed yet....

my approach would be:

async function getsecret_values(client,secret_name) {
  let val = []
  for (let i =0;i<secret_name.length;i++){
    const latestSecret = await client.getSecret(secret_name[i])
    val[i] = latestSecret.value;
  }
  return val  
}

// main:

async function main() {
  let vaultName = result.database;
  const url = `https://${vaultName}.vault.azure.net`;
  const credential = new ClientSecretCredential(result.host, result.user, result.password);
  const client = new SecretClient(url, credential);
  const secret_values = await getsecret_values(client, secrets)
  console.log(secret_values)
}

main()

Related