I am utilizing a DynamoDB service within my Angular project which returns a promise through a series of promises. This process involves retrieving a subId from Cognito and then passing that subId to a DynamoDB get query:
async getUserObject(): Promise<any> {
var promise = new Promise((resolve, reject) => {
setTimeout(() => {
let response;
let cognitoUser = this.cognitoUtil.getCurrentUser();
cognitoUser.getSession(function (err, session) {
if (err)
console.log("UserParametersService: Couldn't retrieve the user");
else {
//Here we're fetching the subId and returning a promise
cognitoUser.getUserAttributes(
function getSubId(err, result) {
let cognitoSubIdPromise = new Promise((resolve,reject) => {
setTimeout(() => {
if (err) {
reject('error');
} else {
let response: any = result[0].getValue();
resolve(response);
}
}, 1000);
});
//Once we've resolved the subId from Cognito we can plug it into our DynamoDB query
cognitoSubIdPromise.then((val) => {
let clientParams:any = {
params: {TableName: environment.ddbTableName}
};
if (environment.dynamodb_endpoint) {
clientParams.endpoint = environment.dynamodb_endpoint;
}
var DDB = new DynamoDB(clientParams);
var getParams = {
TableName: environment.ddbTableName,
Key: {
'userId' : {S: val.toString()},
}
};
//Executing the query
DDB.getItem(getParams,
function (err, result) {
if (err){
console.log(err)
} else {
console.log("DynamoDBService got user object: " + JSON.stringify(result));
response = result;
}
}
);
});
});
}
});
console.log("Async Work Complete");
resolve(response);
}, 1000);
});
return promise;
}
In another user-login service, I am ensuring that a Cognito function callback directing us to the home page of the app after login is only triggered once the db query from my DynamoDB service is completed
databaseDynamo.getUserObject().then((data => {
console.log("this is the resolved data", data);
console.log("getUserObject function execution done!");
callback.cognitoCallback(null, session);
}));
The console log for resolved data always shows as undefined, and the cognito callback function executes before the data has a value. How can I delay the triggering of the cognitoCallBack function until I have the necessary data?