Javascript 如何强制AWS Cognito:signUp()同步执行(nodejs)
我正在尝试设置一个节点应用程序,该应用程序使用AWS cognito sdk注册/登录/确认/验证用户 我目前无法从signUp()方法获取响应,因为代码似乎是异步运行的 我尝试过定义一个异步函数register\u user(…),并将所需的参数传递给一个单独的register(…)函数,以等待注册响应,然后在register\u user(…)内继续 导入语句Javascript 如何强制AWS Cognito:signUp()同步执行(nodejs),javascript,node.js,amazon-web-services,async-await,amazon-cognito,Javascript,Node.js,Amazon Web Services,Async Await,Amazon Cognito,我正在尝试设置一个节点应用程序,该应用程序使用AWS cognito sdk注册/登录/确认/验证用户 我目前无法从signUp()方法获取响应,因为代码似乎是异步运行的 我尝试过定义一个异步函数register\u user(…),并将所需的参数传递给一个单独的register(…)函数,以等待注册响应,然后在register\u user(…)内继续 导入语句 const AmazonCognitoIdentity = require('amazon-cognito-identity-js'
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_user(…)函数中同步运行?非常感谢。如果您想
在注册用户
功能中等待它,您需要更改注册
功能以返回承诺
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)
});
});
}
别忘了把wait
放在try-and-catch-like中
try {
var result = await register(userPool, email, password, attribute_list);
console.log(result);
} catch (e) {
console.error(e); // 30
}
如果一切正常,您将在调用结果中获得cognitoUser,但是如何在任何情况下跟踪错误?