How to return response from cognito async function and display it on the page?

霸气de小男生 提交于 2019-12-13 18:26:25

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!