Ad

Handling Result Of Multiple Async Call And Call The Database After Collecting Result

- 1 answer

Guys, I am new in node js and I am trying to do below steps

1) Calling the AWS API to create the Cognito user by passing data. 2)when all the request will be completed then i will insert all the record in the database.

3) user is the array of all the users.

Here is what I have done

const obj = new ReadCsvFile();
obj.readCSVFromAWS()
    .then(result => {
        const user = obj.getMigratedList();
        for (const i in user) {
            if (user[i] !== null && user[i] !== undefined) {
                const uuid = obj.createUserInCognito(user[i]);
                uuid.then(userAttribute => {
                    user[i].uuid = String(userAttribute.User.Attributes.values); //should complete all the request 
                });
            }
        }
    })
    .catch(err => {
        console.log(err);
    });


public async createUserInCognito(data: User) {
        const CognitoIdentityServiceProvider = AWS.CognitoIdentityServiceProvider;
        const client = new CognitoIdentityServiceProvider({ apiVersion: "2016-04-19" });
        const params = {
            UserPoolId: "us-east-2_lleSjp1bN" /* required */,
            Username: data.email /* required */,
            DesiredDeliveryMediums: ["EMAIL"],
            ForceAliasCreation: false,
            // email_verified: true,
            // MessageAction: "SUPPRESS",
            TemporaryPassword: data.password,
            UserAttributes: [
                {
                    Name: "email" /* required */,
                    Value: data.email
                }
            ]
        };
        return await client.adminCreateUser(params).promise();
    }

Problem

1) I want that all the request should complete of Cognito user.

2) Then I need to pass the list of users into the database.

3) I want to know how can i wait to complete all the request and then insert into the database.

Please help.

Ad

Answer

Use the code snippet written below :

const obj = new ReadCsvFile();
obj.readCSVFromAWS()
    .then(result => {
        const user = obj.getMigratedList();
        for (const i in user) {
            if (user[i] !== null && user[i] !== undefined) {
                obj.createUserInCognito(user[i]).then(uuid=>{
                    uuid.then(userAttribute => {
                        user[i].uuid = String(userAttribute.User.Attributes.values); //should complete all the request 
                    });
                });

            }
        }
    })
    .catch(err => {
        console.log(err);
    });
Ad
source: stackoverflow.com
Ad