After exporting the required modules and setting up the variables
let AWS = require("aws-sdk");
const AmazonCognitoIdentity = require('amazon-cognito-identity-js');
const USER_POOL_ID = 'us-east-1_vkXRQuP4U';
const CLIENT_ID = 'mipa4trls0l7323om33mlk80e8';
const poolData = {
UserPoolId : USER_POOL_ID, ClientId : CLIENT_ID
};
const POOL = new AmazonCognitoIdentity.CognitoUserPool(poolData);
let email = "my.email@domain.com";
let password = "My.Password!";
I can go ahead and call signUp command:
POOL.signUp(email, password, [], null, function(err, result) {
console.log('...result:', result);
});
And it works well. Next I want to wrap the POOL.signUp(email, password...) inside async function sign_up like so:
async function sign_up(email, password) {
POOL.signUp(email, password, [], null, function(err, result) {
console.log('...sign_up.result:', result);
return result;
})
};
async function main() {
let signupData = await sign_up(email, password);
console.log('...main.signupData:', signupData);
return signupData;
};
main().then((error, data) => {console.log('...error, data:', error, data)});
While it works fine, the order of the calls that get executed is wrong as the main function doesn't wait for the sign_up() function to complete. In attempt to correct this behavior I wrap the POOL.signUp(email, password...) inside of Promise:
async function sign_up(email, password) {
return await new Promise((resolve) => {
POOL.signUp(email, password, [], null, {
onSuccess: (result) => {
console.log('...result:', result)
return resolve(result);
},
onFailure: (err) => {
return resolve(err.message);
},
});
})
};
But I am getting the error message:
UnhandledPromiseRejectionWarning: TypeError: callback is not a function
Is there a way to avoid this error?
await the Promise you are returning (since we precisely want our function to be async, we want to defer the waiting to the caller)Promise constructor function needs to provide the second reject parameter to be able to access the callback in the function implementationPOOL.signUp fourth argument, instead of an objectfunction sign_up(email, password) {
return new Promise((resolve, reject) => {
POOL.signUp(email, password, [], null, function(err, result) {
if (err) {
return reject(err.message);
}
console.log('...result:', result)
resolve(result);
});
})
};