AWS Cognito返回未定义错误异步/等待

时间:2018-12-14 13:27:07

标签: javascript node.js aws-sdk

我的问题与this one非常相似,因为我试图将authenticateUser SDK方法包装在Promise中并解决/拒绝该问题。

代码:

async function cognitoAuth(credentials, next, res) {
    const userData = {
        Username: credentials.email,
        Pool: userPool
    };
    const authenticationDetails = getAuthenticationDetails(credentials);

    let userCredentials;
    let authenticatedUserResponse;

    cognitoUser = new CognitoUser(userData);

    try {
        userCredentials = await checkIfAuthenticated(credentials.email);

        if (userCredentials.UserStatus === CognitoUserStatus.FORCE_CHANGE_PASSWORD) {
            res
                .status(203)
                .send(userCredentials);
        } else if (userCredentials.UserStatus === CognitoUserStatus.CONFIRMED) {
            authenticatedUserResponse = await authenticateUser(authenticationDetails);

            console.log(authenticatedUserResponse);
        }
    } catch(err) {
        if (err.message === CognitoErrorMessages.USER_NOT_EXIST) {
            next({
                name: err.message,
                status: 404
            });
        }
    }
}

如您所见,我有2个期待已久的函数checkIfAuthenticatedauthenticateUser。如果checkIfAuthenticated抛出错误并拒绝了诺言,则catch可以使用有效的err对象。

但是,如果authenticateUser引发错误,则会调用catch,但err不确定。

这是我的authenticateUser

function authenticateUser(authenticationDetails) {
    return new Promise((resolve, reject) => {
        cognitoUser.authenticateUser(authenticationDetails, {
            onSuccess: (result) => {
                resolve(merge(err, {
                    res: "SUCCESS"
                }));
            },
            onFailure: (err) => {
                reject(merge(err, {
                    status: 401
                }));
            },
            newPasswordRequired: (userAttrs, requiredAttrs) => {
                resolve(merge(userAttrs, {
                    res: "NEW_PASS_REQ"
                }));
            }
        });
    });
}

使用断点调用onFailure,它是正确的err对象,因此不确定为什么在catch中未定义它

1 个答案:

答案 0 :(得分:0)

弄清楚了。我的一位同事指出,通过在index.js (服务器的入口点)中保存此代码,我对服务器代码运行了babel:

require("@babel/polyfill");
require("@babel/register");

Node中的翻译问题。我一拿出来,改用ES5进出口,就可以正常工作