我正在尝试建立一个使用AWS cognito sdk来注册/登录/确认/认证用户的节点应用程序。
由于代码似乎异步运行,我目前无法从signUp()方法获得响应。
我尝试定义一个异步函数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."
}
};
我发现即使定义了要等待的寄存器功能,该行为仍然是异步的。
有什么方法可以强制signUp方法在register_user(...)函数中同步运行?非常感谢。
答案 0 :(得分:1)
如果您想在register
函数中await
进行更改,则需要更改register_user
函数以返回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);
}
cognitoUser = result.user;
resolve(cognitoUser)
});
});
}
答案 1 :(得分:1)
别忘了像尝试抓住await
一样
try {
var result = await register(userPool, email, password, attribute_list);
console.log(result);
} catch (e) {
console.error(e); // 30
}