Reputation: 1705
From my code snippet below,
import { STS } from 'aws-sdk'
const sts = new STS({
region: 'us-east-1'
});
let accessKeyId: string
let secretAccessKey: string
sts.assumeRole(params, function(err, data) {
if (err) {
console.log(err, err.stack);
} else {
accessKeyId = data.Credentials?.AccessKeyId || '';
secretAccessKey = data.Credentials?.SecretAccessKey || '';
}
});
console.log(accessKeyId);
console.log(secretAccessKey);
VS code says "Variable 'accessKeyId' is used before being assigned." I need to access these two variables outside the assumeRole()
sdk call...how can I make sure the variables are set at that time?
Upvotes: 0
Views: 224
Reputation: 2589
Work in the return block so that it will only process once it the data is returned.
{
if (err) {
console.log(err, err.stack);
} else {
accessKeyId = data.Credentials?.AccessKeyId || '';
secretAccessKey = data.Credentials?.SecretAccessKey || '';
//work here
}
});
Suggestion 2 put into a function that waits async to finish before using the varible
Upvotes: 0
Reputation: 30082
accessKeyId
is being used before it's assigned, because for typescript there is no guarantee that your logs get run before the callback is executed. Without knowing what assumeRole
does, the fact that it takes a callback means it's probably asynchronous, so there will almost certainly be some delay.
As such, if you need to use accessKeyId
, you should do it once it has been assigned after it has been set in the callback.
Upvotes: 2