amazon-cognito-identity-js callbacks

188 Views Asked by At

I am using amazon-cognito-identity-js and the callback looks something like this...

cognitoUser?.getUserAttributes((err, results) => {
  if (err) {
    console.log(err.message || JSON.stringify(err));
    return err.message || JSON.stringify(err);
  }
  if (results != undefined) {
    return results[2].Value;
  }
  return undefined;
});

I can always log the right value here results[2] but, I cannot return this value. I tried using util-promisify but this npm package was designed for Webpack. How do I use a Promise here instead in my Angular application?

This is the getUserAttributes() declaration:

public getUserAttributes(
callback: NodeCallback<Error, CognitoUserAttribute[]>
): void;
1

There are 1 best solutions below

0
On

Turning a callback into a promise is fairly straightforward

const getCognitoUserAttributeByIndex = (i) => new Promise((res, rej) => {
    cognitoUser?.getUserAttributes((err, results) => {
        if (err) {
            rej(err)
            return
        }
        res(results[i].Value)
    })
})