问题
Given the code below, how will I output the response back on the webpage when the response is either success or fail?
loginUser(data) {
var authenticationData = {
Username : data.email,
Password : data.password
};
var authenticationDetails = new AmazonCognitoIdentity.AuthenticationDetails(authenticationData);
var userPool = new AmazonCognitoIdentity.CognitoUserPool(config.cognito);
var userData = {
Username : data.email,
Pool : userPool
};
var cognitoUser = new AmazonCognitoIdentity.CognitoUser(userData);
var output = null;
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: function (result) {
output = result;
return output;
},
onFailure: function(err) {
console.log(err);
},
});
}
<div id="test_mg"></div>
回答1:
You can use an async function
and Promise
in order to get the result from the async call.
function loginUser(data) {
var authenticationData = {};
var authenticationDetails = new AmazonCognitoIdentity.AuthenticationDetails(authenticationData);
var userPool = new AmazonCognitoIdentity.CognitoUserPool(config.cognito);
var userData = {};
var cognitoUser = new AmazonCognitoIdentity.CognitoUser(userData);
var output = null;
return new Promise(function(resolve, reject) {
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: resolve,
onFailure: reject,
});
});
}
async function main() {
try {
var output = await loginUser(data);
} catch(e) {
console.log(e);
}
}
来源:https://stackoverflow.com/questions/52408607/how-to-return-response-from-cognito-async-function-and-display-it-on-the-page