我有一個關于節點和在 if/else 陳述句中呼叫函式的問題。下面是我的情況。我不確定為什么從第一個 IF 陳述句呼叫 awsCreds 函式會起作用,但是當我嘗試從 else 陳述句呼叫它時它不起作用。它是否與我在 else 陳述句中有一個 if/else 的事實有關?
let cacheExpiration;
let currentTime;
let awsCredentials;
async function stsGetCallerIdentity(creds, message) {
const stsParams = { credentials: creds };
// Create STS service object
const kinesis = new AWS.Kinesis(stsParams);
const parsed_value = JSON.parse(message);
const type = parsed_value.type;
console.info(type);
const message_type = {
"transcript": process.env.TRANSCRIPT_KINESIS,
"tone": process.env.TONE_KINESIS,
"pitch": process.env.PITCH_KINESIS
};
const stream_name = message_type[type];
console.info(stream_name);
const params = {
Data: Buffer.from(message),
PartitionKey: `1111`,
StreamName: stream_name
};
kinesis.putRecord(params, function(err, data) {
if (err) console.error(err);
else {
console.info(JSON.stringify(data));
}
});
}
function awsCreds() {
return new Promise((resolve, reject) => {
const roleToAssume = {
RoleArn: process.env.IAMRole,
RoleSessionName: `session1`,
DurationSeconds: 900 };
sts.assumeRole(roleToAssume, function(err, data) {
if (err) {
console.error(err, err.stack);
reject(err.stack);
} else {
awsCreds = {
accessKeyId: data.Credentials.AccessKeyId,
secretAccessKey: data.Credentials.SecretAccessKey,
sessionToken: data.Credentials.SessionToken,
cacheExpiration: data.Credentials.Expiration
};
resolve(awsCreds);
}
});
});
};
webSocketClient.on(`message`, async (message) => {
try {
currentTime = new Date();
console.log(`currentTime`, currentTime);
console.log(`cacheExpiration`, cacheExpiration);
if (cacheExpiration == undefined) {
//Calling awsCreds returns values.
awsCredentials = await awsCreds();
stsGetCallerIdentity(awsCredentials, message)
} else {
const minutes = (cacheExpiration.getTime() - currentTime.getTime());
console.log(`minutes`, minutes);
if (minutes > 60000) {
//Do something
stsGetCallerIdentity(awsCredentials, message)
} else {
// Calling awsCreds from here returns error 'awsCreds is not a function'.
console.log(`Refreshing credentials`);
awsCredentials = await awsCreds();
stsGetCallerIdentity(awsCredentials, message)
}
}
} catch (error) {
console.error(`There was an error`, error);
};
)};
uj5u.com熱心網友回復:
你的函式被呼叫awsCreds,然后你awsCreds在你之前分配為一個物件文字resolve,你需要const在前面,或者根本不分配只是把物件放在決議中:
改變
awsCreds = {
accessKeyId: data.Credentials.AccessKeyId,
secretAccessKey: data.Credentials.SecretAccessKey,
sessionToken: data.Credentials.SessionToken,
cacheExpiration: data.Credentials.Expiration
};
resolve(awsCreds);
到
resolve({
accessKeyId: data.Credentials.AccessKeyId,
secretAccessKey: data.Credentials.SecretAccessKey,
sessionToken: data.Credentials.SessionToken,
cacheExpiration: data.Credentials.Expiration
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/369281.html
標籤:节点.js
