2 回答
TA贡献1883条经验 获得超3个赞
由于您的变量secreretAccesKeyParam是一个承诺,因此您将无法访问secretAccessKey承诺处理程序(例如)的上下文(例如function (data, err) {...})。根据承诺的定义这样做:
const myPromise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('foo');
}, 300);
});
var myRes = 'bar';
myPromise.then(dunction (data, err) {
myRes = data;
console.log(myRes); // executed asynchronously
});
console.log(data); // executed sychronously so printed first. myRes value is still 'bar'.
会给你输出:
'bar'
'foo'
如果您想像同步一样处理事情,您可能想要做的是使用异步函数。
var options = {
Name: 'SecretAccessKey_temp',
WithDecryption: true
};
var secreretAccesKeyParam = ssm.getParameter(options).promise();
(async () => {
try {
const data = await secreretAccesKeyParam;
} catch (err) {
console.log(err, err.stack);
}
const secretAccessKey = data.Parameter.Value;
console.log(secretAccessKey);
... // any action with your secret access key
})();
或者,如果您稍后已经在使用处理程序函数:
let _secretAccessKey;
const getSecretAccessKey = async () => {
if (!_secretAccessKey) {
try {
const data = await secreretAccesKeyParam;
} catch (err) {
console.log(err, err.stack);
return null;
}
_secretAccessKey = data.Parameter.Value;
}
return Promise.resolve(_secretAccessKey);
}
...
async function mySuperHandler() {
const secretAccessKey = await getSecretAccessKey();
// do something with the secret
}
TA贡献1827条经验 获得超7个赞
将其设置为 env 怎么样?我目前使用此方法,但您必须确保在使用它之前设置 env 。
secreretAccesKeyParam.then(function (data, err) {
if (err) console.log(err, err.stack);
else {
process.env.secretAccessKey = data.Parameter.Value;
const secretAccessKey = process.env.secretAccessKey;
console.log(secretAccessKey);
}
});
添加回答
举报