gpt4 book ai didi

javascript - 如何强制 AWS Cognito : signUp() to execute synchronously (nodejs)

转载 作者:行者123 更新时间:2023-12-05 00:58:51 24 4
gpt4 key购买 nike

我正在尝试设置一个 Node 应用程序,该应用程序使用 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(...) 函数中同步运行?非常感谢。

最佳答案

如果你想在 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)
});
});
}

关于javascript - 如何强制 AWS Cognito : signUp() to execute synchronously (nodejs),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56007754/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com