Force cognito sdk function getUserAttributes to execute synchronously

时间:2019-04-16 23:30:44

标签: javascript amazon-web-services sdk amazon-cognito

Calling SDK function cognitoUser.getUserAttributes (from within a browser), I can see the function is getting called in the background.

Code is called by including a js script from the main html page. The script executes in a JQuery wrapper and it is returning before all the code has executed. Specifically, I can see in the console output that a series of lines is executed out of order. I need to wait until all code from the js completes before I continue because I need some of those values.

Tried await, promise syntax and just about everything else I could Google from Amazon and Stack...

Console Log output (excerpt):

  You are now logged in., cognito-auth.js:58
  Auth1: undefined, cognito-auth.js:81
  Auth3: undefined, cognito-auth.js:98
  Page: undefined, form-apply.html:161
     {other output here as well from additional js and HTML pages}
  Auth2: 123456, cognito-auth.js:96

HTML code:

...
    <script src="js/cognito-auth.js"></script>
    <script type="text/javascript">console.log('Page: ' + COG.CAPID);</script>    
...

js/cognito-auth.js:

...
console.log('Auth1: ' + COG.CAPID);
        cognitoUser.getUserAttributes ( function(err, result) {
            if (err) {
                alert(err);
                return;
            }
            for (i = 0; i < result.length; i++) {
                if ( result[i].getName() == "custom:CAPID" ) {
                    COG.CAPID = (' ' + result[i].getValue()).slice(1);
                } else if ( result[i].getName() == "email" ) {
                    COG.Email = result[i].getValue();
                } else if ( result[i].getName() == "phone_number" ) {
                    COG.PhoneNumber = result[i].getValue();
                }
            }
console.log('Auth2: ' + COG.CAPID);
        });
console.log('Auth3: ' + COG.CAPID);

I expect the output from Auth1, Auth2 and Auth3 to be in order. But clearly Auth3 is executing before Auth2. There is also output from additional JS and HTML files that should not be executing until the completion of the getUserAttributes.

0 个答案:

没有答案