异步/等待aws sdk功能

时间:2020-06-18 17:07:48

标签: node.js aws-sdk

我正在使用自定义身份验证质询来获取otp作为响应,使用以下代码可以获取OTP。但是,除了promise之外,我如何使用async / await从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);
                }
            });
        });
    }```

1 个答案:

答案 0 :(得分:0)

创建一个异步函数。在try / catch块中使用“ 等待”捕获任何错误。

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