0

I am using a custom auth challenge to get the otp as response, with below code I am able to get the OTP. But, instead of promise how can I use async/await to get the response from intiateAuth.

        const params = {
            AuthFlow: ".......",
            ClientId: "*********",
            AuthParameters: {
                "USERNAME": req.userName,
            }
        };
        return new Promise((resolve, reject) => {
            new AWS.CognitoIdentityServiceProvider().initiateAuth(params, (err, data) => {
                if (err) {
                    console.log("Error in adminInitiateAuth: %s", err.message);
                    reject(false);
                } else {
                    const otpResponse: IOTPResponseDetails = {
                        session: data.Session,
                        userName: data.ChallengeParameters.USERNAME,
                    }
                    resolve(otpResponse);
                }
            });
        });
    }```
Rewa
  • 1
  • 2
  • Have you tried `var data = await new AWS.CognitoIdentityServiceProvider().initiateAuth(params)`? – Molda Jun 18 '20 at 17:13
  • Does this answer your question? [How to use Async and Await with AWS SDK Javascript](https://stackoverflow.com/questions/51328292/how-to-use-async-and-await-with-aws-sdk-javascript) – Chris Jun 18 '20 at 17:18

1 Answers1

0

Create an async function. Use "await" inside a try/catch block to capture any errors.

const params = {
  AuthFlow: ".......",
  ClientId: "*********",
  AuthParameters: {
    "USERNAME": req.userName,
  }
};

// Async function using await        
const execute = async(parameters) => {
  try {
    const data = await new AWS.CognitoIdentityServiceProvider().initiateAuth(parameters);

    const otpResponse: IOTPResponseDetails = {
      session: data.Session,
      userName: data.ChallengeParameters.USERNAME,
    };

    return otpResponse;
  } catch (err) {
    console.log("Error in adminInitiateAuth: %s", err.message);
    throw new Error(err.message);
  }
}

// Call async function with params as argument
await execute(params);
Lahiru Tennakoon
  • 621
  • 1
  • 6
  • 8