'javascript async/await not waiting in AWS Lambda?
I'm learning AWS lambda and I'm also new to JavaScript. Always a great idea to have multiple variables in play at the same time. But, I've written 2 version of the code below. The first works. The second does not and I cannot figure out why.
The only difference between the 2 programs is that I've created the addUser function to execute the Cognito call.
Working code:
const moment = require('moment');
const AWS = require('aws-sdk');
const waitup = require('await-to-js');
exports.handler = async(event)=>{
let body=JSON.parse(event.body);
let email=body.email;
let fullName=body.name;
let password=body.password;
let phoneNumber=body.phoneNumber;
const cognitoParams = {
UserPoolId: "ab-west-6_FRz8PQp3t",
Username: email,
TemporaryPassword: Math.random().toString(36).substr(2, 10),
UserAttributes: [{
Name: "email",
Value: email,
},
{
Name: "email_verified",
Value: "true",
},
]
};
let actResponse;
var cognito = new AWS.CognitoIdentityServiceProvider();
try {
actResponse=await cognito.adminCreateUser(cognitoParams).promise();
console.log("actResponse", actResponse);
} catch(err) {
console.log("err", err, err.stack);
actResponse = err;
}
return {
statusCode: 200,
body: JSON.stringify(actResponse)
};
}
Non-working code:
const moment = require('moment');
const AWS = require('aws-sdk');
const waitup = require('await-to-js');
async function addUser(email, fullName, phoneNumber){
var cognito = new AWS.CognitoIdentityServiceProvider();
const cognitoParams = {
TemporaryPassword: Math.random().toString(36).substr(2, 10),
UserPoolId: "ab-west-6_XXx4VVq",
Username: email,
UserAttributes: [{
Name: "email",
Value: email,
},
{
Name: "email_verified",
Value: "true",
},
]
};
try {
let response = await cognito.adminCreateUser(cognitoParams).promise();
return response;
} catch(err) {
return err;
}
}
exports.handler = async(event)=>{
let body=JSON.parse(event.body);
console.log("body", body);
let email=body.email;
let fullName=body.name;
let phoneNumber=body.phoneNumber;
const accountResponse=addUser(email, fullName, phoneNumber);
return {
statusCode: 200,
body: JSON.stringify(accountResponse)
};
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
