如何强制AWS Cognito:signUp()在Node.js中同步执行

3

我正在尝试建立一个使用AWS Cognito SDK注册/登录/确认/认证用户的Node应用程序。

由于代码似乎是异步运行的,因此我目前无法从signUp()方法中获得响应。

我尝试定义一个async函数register_user(...),并将所需参数传递给一个单独的register(...)函数来等待signUp响应,然后在register_user(...)内部继续执行。

导入语句

const AmazonCognitoIdentity = require('amazon-cognito-identity-js');
const CognitoUserPool = AmazonCognitoIdentity.CognitoUserPool;
const AWS = require('aws-sdk');
const request = require('request');
const jwkToPem = require('jwk-to-pem');
const jwt = require('jsonwebtoken');
global.fetch = require('node-fetch');

注册函数

function register(userPool, email, password, attribute_list){

    let response;

    userPool.signUp(email, password, attribute_list, null, function(err, result){
        console.log("inside")
        if (err){
            console.log(err.message);
            response = err.message;
            return response;
        } 
        cognitoUser = result.user;
    });

    return "User succesfully registered."

}

用户注册

var register_user = async function(reg_payload){

    email = reg_payload['email']
    password = reg_payload['password']
    confirm_password = reg_payload['confirm_password']

    // define pool data
    var poolData = {
      UserPoolId : cognitoUserPoolId,
      ClientId : cognitoUserPoolClientId
    };

    var userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);

    var attribute_list = [];

    // define fields needed
    var dataEmail = {
        Name : 'email',
        Value : email
    };

    var attributeEmail = new AmazonCognitoIdentity.CognitoUserAttribute(dataEmail);

    attribute_list.push(attributeEmail);

    if (password === confirm_password){

        console.log("here")

        var result = await register(userPool, email, password, attribute_list);

        console.log(result)

        console.log("here2")

    } else {
        return "Passwords do not match."
    }
};


我发现即使我已经指定了register函数为await,其行为仍然是异步的。
有没有办法在register_user(...)函数中强制同步运行signUp方法?非常感谢。
2个回答

6

如果您希望在register_user函数中使用await,则需要将register函数更改为返回一个Promise。

function register(userPool, email, password, attribute_list) {
  return new Promise((resolve, reject) => {
    userPool.signUp(email, password, attribute_list, null, (err, result) => {
      console.log('inside');
      if (err) {
        console.log(err.message);
        reject(err);
        return;
      }
      cognitoUser = result.user;
      resolve(cognitoUser)
    });
  });
}

如果一切正常,您将在调用的结果中获得cognitoUser,但是如何跟踪任何错误呢? - Eric

2
不要忘记在 try 和 catch 中加入 await,例如:
 try {
        var result = await register(userPool, email, password, attribute_list);

        console.log(result);
    } catch (e) {
        console.error(e); // 30
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接