简体   繁体   English

如何等到我从 Node JS 中的 Keyvault 获得秘密值?

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

I am fairly new to Javascript and I understand that it executes asynchronously.我对 Javascript 相当陌生,我知道它是异步执行的。 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这是获取 keyvault 机密值的 function

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我正在从主块调用 getsecret_values function

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. console.log 都返回空数组。

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.我希望我的代码等到获取秘密值并将其放入secret_values数组中,然后继续执行下一个代码块。 How do I achieve this?我如何实现这一目标?

the easiest way is to use Async Await pattern, which uses promises in the background.最简单的方法是使用 Async Await 模式,它在后台使用 Promise。 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;
  }
  callback(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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM