如何从Cognito异步函数返回响应并将其显示在页面上? [英] How to return response from cognito async function and display it on the page?

查看:97
本文介绍了如何从Cognito异步函数返回响应并将其显示在页面上?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下代码,当响应成功或失败时,如何在网页上输出响应?

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>


推荐答案

您可以使用 async函数 Promise ,以便从异步调用中获取结果。

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);
    }
}

这篇关于如何从Cognito异步函数返回响应并将其显示在页面上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆