0

I'm calling this function to retrieve a user attribute, however when i'm testing the function the return result is always "test" and then it goes through "cognitoUser.getUserAttributes" and logs the actual result. I'm not sure why but "cognitoUser.getUserAttributes" seems to be skipped initially.

when run, it prints out test and instead of the actual result

any ideas?

function retrieveattribute(e) {
  var ans = "test";
  var e = "custom:InstanceID_1";
  cognitoUser.getUserAttributes(function(err, result) {
    if (err) {
      alert(err);
      return;
    }
    for (i = 0; i < result.length; i++) {
      if (result[i].getName() == e) {
        ans = result[i].getValue();
        console.log(ans);
        return ans;
      }
    }
  });
  return ans;
}
Eddie
  • 26,593
  • 6
  • 36
  • 58
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – str Apr 26 '19 at 15:35
  • The return statement inside the the callback function only returns from the callback function. Instead of using a callback you should write ans = await cognitoUser.getUserAttributes() – Matthew James Briggs Apr 26 '19 at 15:38
  • Hi Matthew, do you mind expanding on that a little please? – RetroGamer7 Apr 26 '19 at 16:19

1 Answers1

0

For start "async code" you need wrap you function to promise:

function retrieveattribute(e) {
    return new Promise(function(res) {
        var ans = "test";
        var e = "custom:InstanceID_1";

        cognitoUser.getUserAttributes(function(err, result) {
            if (err) {
                alert(err);
                return;
            }
            for (i = 0; i < result.length; i++) {
                if (result[i].getName() == e) {
                    ans = result[i].getValue();
                    console.log(ans);
                    res(ans);
                }
            }
        });
    })
}

After it you can use as promise:

   retrieveattribute(e).then(t => console.log(t))

Or await it at async function:

   await retrieveattribute(e)
Tim Times
  • 422
  • 4
  • 8