簡體   English   中英

如何強制 AWS Cognito:signUp() 同步執行(nodejs)

[英]How to force AWS Cognito: signUp() to execute synchronously (nodejs)

我正在嘗試設置一個節點應用程序,該應用程序使用 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)
    });
  });
}

不要忘記將await放入 try 和 catch 中

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM